有三个线程轮流打印,要求让它们交替输出 1、2、3

2020-06-11  本文已影响0人  thomasyoungs

问题提出

有三个线程,要求让它们交替输出 1、2、3,打印内容如下:

线程1:1

线程2:2

线程3:3

线程1:1

线程2:2

线程3:3

……


问题分析

这类题是多线程比较典型的一道题,我也看到网上好多类似的题和解法,有的要设置flag,有的用到多个锁,感觉他们把这道题搞复杂了。题目涉及知识点是 wait() 和 notify(),符合要求的线程进来可以打印,打印后释放资源,notifyAll()让所有线程重新抢占,不符合条件的线程需要等待,调用wait(),出让资源。

话不多说直接贴代码

import java.util.concurrent.atomic.AtomicInteger;

/**

* Author:yangzhikuan

* Date:2020-04-20

* Description:Test

*/

public class Test {

public static void main(String[] args) {

MyRunnale myRunnale =new MyRunnale();

        Thread thread =new Thread(myRunnale, "0");

        Thread thread1 =new Thread(myRunnale, "1");

        Thread thread2 =new Thread(myRunnale, "2");

        thread.start();

        thread1.start();

        thread2.start();

    }

static class MyRunnaleimplements Runnable {

private final AtomicIntegeratomicInteger;

        MyRunnale() {

this.atomicInteger =new AtomicInteger();

        }

@Override

        public void run() {

while (true) {

synchronized (atomicInteger) {

String name = Thread.currentThread().getName();

                    int count = Integer.valueOf(name);

                    int current =atomicInteger.get();

                    if(current >15){

break;

                    }

//                    System.out.println(name + "  " + current);

                    if (current %3 == count) {//当前线程可以打印

                        System.out.println("  current Thread "+name +"  ---->  " + current);

                        atomicInteger.set(current +1);

                        atomicInteger.notifyAll();

                    }else {

try {

atomicInteger.wait();

                        }catch (InterruptedException e) {

e.printStackTrace();

                        }

}

}

}

}

}

}

上一篇 下一篇

猜你喜欢

热点阅读