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