一道经典的Java多线程编程题

问题:

启动3个线程打印递增的数字, 线程1先打印1,2,3,4,5, 然后是线程2打印6,7,8,9,10, 然后是线程3打印11,12,13,14,15. 接着再由线程1打印16,17,18,19,20....以此类推, 直到打印到75. 程序的输出结果应该为:


思路: 通过取模实现有序打印


package com.test;

public class LockTest1 {

    public static void main(String[] args) {
        final LockNum lockNum = new LockNum();

        lockNum.setCount(1);

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                while (lockNum.getCount() < 70) {
                        int num = (lockNum.getCount() / 5) % 3;
                        int priority = Thread.currentThread().getPriority() - 1;
                        if (num == priority) {
                            for (int i = 0; i < 5; i++) {
                                if(lockNum.getCount() > 75){
                                    continue;
                                }
                                System.out.println("当前线程: " + Thread.currentThread().getName() + "--->" + lockNum.getCount());
                                lockNum.setCount(lockNum.getCount() + 1);
                            }
                        }
                }
            }
        };

        Thread t1 = new Thread(runnable);
        t1.setName("T1");
        t1.setPriority(1);
        Thread t2 = new Thread(runnable);
        t2.setName("T2");
        t2.setPriority(2);
        Thread t3 = new Thread(runnable);
        t3.setName("T3");
        t3.setPriority(3);
        t1.start();
        t2.start();
        t3.start();
    }
}

class LockNum {

    private Integer count;

    public Integer getCount() {
        return count;
    }

    public void setCount(Integer count) {
        this.count = count;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值