问题描述
创建两个线程交替打印1-100
思路
线程1进入run(),执行完打印和count++操作,调用wait()方法释放锁,线程2进入run(),notifyAll()唤醒线程1并获取锁,执行完打印和count++操作,调用wait()释放锁,重复执行…
代码实现
public class 创建两个线程交替打印1到100 implements Runnable{
public int count = 1;
@Override
public void run() {
while(true){
synchronized (this){
notifyAll();
if(count <= 100){
System.out.println(Thread.currentThread().getName()+":"+count);
count++;
try{
wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}else{
return;
}
}
}
}
}
public class 测试类 {
public static void main(String[] args) {
创建两个线程交替打印1到100 res = new 创建两个线程交替打印1到100();
Thread thread1 = new Thread(res);
Thread thread2 = new Thread(res);
thread1.setName("线程1");
thread2.setName("线程2");
thread1.start();
thread2.start();
}
}
运行结果: