2019-12-21

public class ThreadClass implements Runnable {

private int num = 1;
private int s = 1;
@Override
public void run() {
    while(s<=10){
        synchronized (this){
            if(num%2==1&&Thread.currentThread().getName().equals("Puppy1")||num%2==0&&Thread.currentThread().getName().equals("Puppy2")){
                System.out.println(Thread.currentThread().getName() + s + (s+1));
                s+=2;
                num++;
                this.notifyAll();
                
            }else{
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
public static void main(String[] args) {

    ThreadClass threadClass = new ThreadClass();
    Thread t1 = new Thread(threadClass,"Puppy1");
    Thread t2 = new Thread(threadClass,"Puppy2");
    t1.start();
    t2.start();
}

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容