两个线程交替打印数字(看了就懂版)
Posted 小宝的进化之路
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了两个线程交替打印数字(看了就懂版)相关的知识,希望对你有一定的参考价值。
/** * @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; } }
以上是关于两个线程交替打印数字(看了就懂版)的主要内容,如果未能解决你的问题,请参考以下文章