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();
}

}

你可能感兴趣的:(2019-12-21)