两个线程交替打印数字

这篇博客展示了如何使用多线程让两个线程交替打印数字,从0到9,详细记录了每个线程打印的数字顺序。

public class PrintNum {
    public static void main(String[] args) {
        Task task = new Task();
        Thread thread1 = new Thread(task);
        thread1.setName("thread1");
        Thread thread2 = new Thread(task);
        thread2.setName("thread2");

        thread1.start();
        thread2.start();

    }
}

class Task implements Runnable{

    private volatile boolean flag = false;
    private volatile int count = 0;

    @Override
    public void run() {
        while (true){
            if ("thread1".equals(Thread.currentThread().getName()) && !flag && count < 10){
                System.out.println(Thread.currentThread().getName() + "打印数字" + count++);
                flag = true;
            }
            if ("thread2".equals(Thread.currentThread().getName()) && flag && count < 10){
                System.out.println(Thread.currentThread().getName() + "打印数字" + count++);
                flag = false;
            }
        }
    }
}

结果
thread1打印数字0
thread2打印数字1
thread1打印数字2
thread2打印数字3
thread1打印数字4
thread2打印数字5
thread1打印数字6
thread2打印数字7
thread1打印数字8
thread2打印数字9

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值