使用两个线程打印 1-100。线程1, 线程2 交替打印
class Communication implements Runnable{
int i = 1;
@Override
public void run() {
while(true){
synchronized (this){
notify();
if(i <= 100){
System.out.println(Thread.currentThread().getName() + ":"+ i++);
}else{
break;
}
try{
wait();
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
}
}
public class test1 {
public static void main(String[] args) {
Communication communication = new Communication();
Thread t1 = new Thread(communication);
Thread t2 = new Thread(communication);
t1.setName("线程一");
t2.setName("线程二");
t1.start();
t2.start();
}
}