main.class
public class Solution1006 {
public static void main(String[] args) {
MyObject my = new MyObject();
new Thread(new Runnable() {
@Override
public void run() {
for(int i=0; i<10; i++)
my.printOdd();
}
},"奇数线程").start();
new Thread(new Runnable() {
@Override
public void run() {
for(int i=0; i<10; i++)
my.printEven();
}
},"偶数线程").start();
}
}
MyObject.class
public class MyObject {
private static int num = 1;
public synchronized void printOdd(){
while(num%2 == 0){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + ": " + num);
num++;
this.notifyAll();
}
public synchronized void printEven(){
while(num%2 != 0){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + ": " + num);
num++;
this.notifyAll();
}
}
结果:

本文通过一个Java程序实例,展示了如何使用synchronized关键字和wait/notifyAll方法实现两个线程的交替打印奇数和偶数。该程序创建了一个共享资源MyObject,并启动了两个线程,分别负责打印奇数和偶数,通过线程间的等待和通知机制确保了正确的打印顺序。
788

被折叠的 条评论
为什么被折叠?



