码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2020-11-20 11:56:39      阅读:13      评论:0      收藏:0      [点我收藏+]

标签:extend   dex   end   auth   exce   swap   run   start   +=   

/**
 * @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;
    }
}

 

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

标签:extend   dex   end   auth   exce   swap   run   start   +=   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!