使用线程顺序打印数字

实现思路:要顺序打印数字,首先要保证打印处于同步的语句块中,这个可以用synchronized实现;其次,可以采用线程顺序来保证数字顺序,在for循环中开启线程,可以保证线程是有序的。

package com.xicheng.bigdata;

/**
 * @author liubin52
 * @date 2018/11/6
 * @description
 */
public class PrintSequenceTest implements Runnable{

    private static final Object LOCK = new Object();

    // 当前数字
    private static int currentNo = 0;
    // 线程编号
    private int threadNo;
    // 线程总数
    private int threadCnt;
    // 数字总数
    private int max;

    public PrintSequenceTest() {
    }

    public PrintSequenceTest(int max, int threadNo, int threadCnt) {
        this.max = max;
        this.threadCnt = threadCnt;
        this.threadNo = threadNo;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (LOCK) {
                while (currentNo % threadCnt != threadNo) {
                    if (currentNo > max) {
                        break;
                    }
                    try {
                        LOCK.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                if (currentNo > max) {
                    break;
                }
                System.out.println("Thread-" + threadNo + ":" + currentNo);
                currentNo++;
                LOCK.notifyAll();
            }
        }
    }

    public static void main(String[] args) {
        int threadCnt = 3;
        int max = 10;
        for(int i = 0; i < threadCnt; i++) {
            new Thread(new PrintSequenceTest(max, i, threadCnt)).start();
        }
    }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值