62,612
社区成员
发帖
与我相关
我的任务
分享
public class Test2 {
//要求:制作两个线程对象,要求用同步块的方式使第一个线程运行2次,然后将自己阻塞起来,唤醒
//第二个线程,第二个线程再运行2次,然后将自己阻塞起来,唤醒第一个线程……两个线程交替执行。
public static void main(String[] args) {
Print1 p = new Print1();
MyThread1 myThread = new MyThread1(p);
new Thread(myThread, "线程1").start(); //开启线程1
new Thread(myThread, "线程2").start(); //开启线程2
}
}
class MyThread1 implements Runnable {
private Print1 p;
public MyThread1(Print1 p) {
this.p = p;
}
@Override
public void run() {
while(true){
p.method();
}
}
}
class Print1 {
private Object obj = new Object();
public void method() {
synchronized (obj) {
obj.notifyAll();
for(int i = 0;i < 2;i++){
System.out.println(Thread.currentThread().getName() + " is doing something!");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}