天天看点

java 中的wait和notify以及synchronized的使用,实现两个线程交替执行

public class TestThread  extends Thread{

    private static int n=1;

    private static Object o=new Object();

    public void run() {

        synchronized (o) {

            while(n>=0&&n<=1){

                try {

                    Thread.sleep(200);

                } catch (InterruptedException e) {

                    e.printStackTrace();

                }

                if(currentThread().getName().equals("A")){

                n--;

                    o.notify();

                    System.out.println(n);

                    try {

                        o.wait();

                    } catch (InterruptedException e) {

                        e.printStackTrace();

                    }

                }

                else if (currentThread().getName().equals("B")) {

                n++;

                    o.notify();

                    System.out.println(n);

                    try {

                        o.wait();

                    } catch (InterruptedException e) {

                        e.printStackTrace();

                    }

                }

                }

            }

        }

        public static void main(String[] args) {

        TestThread b=new TestThread();

        TestThread a=new TestThread();

        a.setName("A");

        b.setName("B");

             a.start();

             b.start();

        }

}