多个线程按顺序打印

思路:多个线程争抢同一把锁,但只有当前执行顺序和本线程匹配才执行打印操作,因而,如果顺序不对,即便抢到锁也要释放

package thread;
import java.util.concurrent.atomic.AtomicInteger;

public class ThreadOrderPrint {
    public static void main(String[] args)
    {
        AtomicInteger runOrder =new AtomicInteger(0);
        
        int count =5;
        Mythread threadA =new Mythread(0,count,1,runOrder);
        Mythread threadB =new Mythread(1,count,2,runOrder);
        Mythread threadC =new Mythread(2,count,3,runOrder);
        Mythread threadD =new Mythread(3,count,4,runOrder);
        Mythread threadE =new Mythread(4,count,5,runOrder);
        
        threadA.start();
        threadB.start();
        threadC.start();
        threadD.start();
        threadE.start();
    }
    
    public static class Mythread extends Thread{
        public int order;//执行的顺序
        public int count;//需要按顺序执行的线程数量
        public int value;//本线程实例需要打印的值
        public AtomicInteger runOrder;//外部传入的共享变量
        public Mythread(int order,int count, int value,AtomicInteger runOrder)
        {
            this.order =order;
            this.count =count;
            this.value =value;
            this.runOrder =runOrder;
        }
        public void run()
        {
            while(true)
            {
                synchronized(runOrder)
                {
                    if(runOrder.get()%count ==order)
                    {
                        System.out.println(value);
                        runOrder.getAndAdd(1);
                        value +=5;
                        runOrder.notifyAll();
                        try {
                            Thread.sleep(100);
                        }catch(InterruptedException e) {
                            
                        }
                    }
                    else {
                        try {
                            runOrder.wait();
                        }catch(InterruptedException e) {
                            
                        }
                    }
                }
            }
            
        }
    }

}
 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值