多线程:实现三个线程轮流打印1-100的数字

多线程:实现三个线程轮流打印1-100的数字_第1张图片

前言

  • 字节跳动笔试题
public class ThreadTest02 {

    public static void main(String[] args) throws InterruptedException {

        SynchronousQueue<Integer> one2two = new SynchronousQueue<>();
        SynchronousQueue<Integer> two2three = new SynchronousQueue<>();
        SynchronousQueue<Integer> three2one = new SynchronousQueue<>();

        new Thread(new PrintTask(three2one, one2two)).start();
        new Thread(new PrintTask(one2two, two2three)).start();
        new Thread(new PrintTask(two2three, three2one)).start();

        three2one.put(1);

    }

}

class PrintTask implements Runnable {

    private SynchronousQueue<Integer> in;
    private SynchronousQueue<Integer> out;

    public PrintTask(SynchronousQueue<Integer> in, SynchronousQueue<Integer> out) {
        this.in = in;
        this.out = out;
    }

    @Override
    public void run() {

        try {

            long id = Thread.currentThread().getId();

            int data = 0;
            while (true) {
                data = in.take();
                System.out.println("当前线程:" + id + "打印数字为:" + data);

                /**
                 * 下一个数字超过范围了,没必要在传递给下一个线程了
                 */
                if (data + 1 <= 100)
                    out.put(data + 1);

                /**
                 * 本线程负责打印的下一个数字,已经超过范围了,本线程可以结束了
                 */
                if (data + 3 > 100)
                    break;
            }

        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
} 
  • 运行结果

多线程:实现三个线程轮流打印1-100的数字_第2张图片

你可能感兴趣的:(JUC多线程,java)