public class MultiThreadPrint {
public static void main(String[] args) {
Object o = new Object();
new Thread(new NumberPrintRunnable1(o)).start();
new Thread(new NumberPrintRunnable2(o)).start();
}
}
class NumberPrintRunnable1 implements Runnable {
private Object obj;//声明一个类的引用
//通过构造器将共享资源传进来
public NumberPrintRunnable1(Object obj) {
this.obj = obj;
}
public void run() {
synchronized (obj) {
for (int i = 0; i < 90; i+=2) {
System.out.println(i+1);
obj.notifyAll();
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
class NumberPrintRunnable2 implements Runnable {
private Object obj;//声明一个类的引用
//通过构造器将共享资源传进来
public NumberPrintRunnable2(Object obj) {
this.obj = obj;
}
public void run() {
synchronized (obj) {
for (int i = 1; i < 90; i+=2) {
System.out.println(i + 1);
obj.notifyAll();
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
Practice-两个线程交替打印1-90(Java)
最新推荐文章于 2024-08-12 21:14:17 发布