两个线程交替打印数字(看了就懂版)

/**
 * @description:
 * @author: 
 * @create: 2020-11-15 21:12
 **/
public class SwapThread {

    static class Mythread1 extends Thread {


        public void run() {
            synchronized (SwapThread.class) {

                for (int i = 2; i < 1000; i += 2) {
                    System.out.println("--" + i);
                    SwapThread.class.notify();
                    try {
                        SwapThread.class.wait();
                        if (i == 998) {
                            //最后一次的wait ,自己notify。要不然程序结束不了
                            SwapThread.class.notify();
                        }
                    } catch (InterruptedException e) {
                        System.out.println("cao,异常了"+e);
                    }
                }
            }
        }
    }

    static class Mythread2 extends Thread {
        public void run() {
            synchronized (SwapThread.class) {
                for (int i = 1; i < 1000; i += 2) {
                    System.out.println("-----" + i);
                    SwapThread.class.notify();
                    try {
                        SwapThread.class.wait();
                        if (i == 999) {
                            //最后一次的wait ,自己notify。要不然程序结束不了
                            SwapThread.class.notify();
                        }
                    } catch (InterruptedException e) {
                         System.out.println("cao,异常了"+e);
                    }
                }
            }
        }
    }

    public static void main(String[] args) {
// 0-1000
        Mythread2 mythread2 = new Mythread2();
        Thread thread2 = new Thread(mythread2);
        thread2.start();
        Mythread1 mythread1 = new Mythread1();
        Thread thread1 = new Thread(mythread1);
        thread1.start();

        return;
    }
}

 

posted @ 2020-11-15 22:06  小宝的进化之路  阅读(135)  评论(0编辑  收藏  举报