线程交替输出100个数,线程1输出单数,线程2输出双数

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();
                    }
                }
            }
        }
    }
}
输出结果:
 

猜你喜欢

转载自www.cnblogs.com/javalim/p/10617481.html