首页 > 编程语言 > 详细

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

时间:2020-11-15 23:04:01      阅读:114      评论:0      收藏:0      [点我收藏+]
/**
 * @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;
    }
}

 

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

原文:https://www.cnblogs.com/xbjhs/p/13982637.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!