package thread;
public class TestThread{
/**
* @param args
*/
public static void main(String[] args) {
ThreadPrint t=new ThreadPrint();
Thread th1=new Thread(t,"线程1");
Thread th2=new Thread(t,"线程2");
th2.start();
th1.start();
}
}
class ThreadPrint implements Runnable{
int i=1;
boolean flag=true;
@Override
public void run() {
while(i<=100){
synchronized(this){
flag=(i==1)?(("线程1".equals(Thread.currentThread().getName()))?true:false):true;
if(flag){
this.notifyAll();
System.out.println(Thread.currentThread().getName() + ":" + i);
i++;
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
输出结果: