600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > java 控制线程的顺序_【Java多线程系列四】控制线程执行顺序

java 控制线程的顺序_【Java多线程系列四】控制线程执行顺序

时间:2021-11-02 16:35:43

相关推荐

java 控制线程的顺序_【Java多线程系列四】控制线程执行顺序

packagecom.concurrent.test;importjava.util.concurrent.CountDownLatch;importorg.junit.Assert;importorg.junit.Test;/*** 规定线程的执行顺序*/

public classThreadOrderTest {private long millisUnit = 1000;private int count = 2;classThreadOrder {/** join方法使多个线程依次执行*/

public long preserveOrderViaJoin() throwsInterruptedException {long startMillis =System.currentTimeMillis();

Thread tmp;for (int i = 0; i < count; i++) {

tmp= new Thread(newRunnable() {

@Overridepublic voidrun() {try{

Thread.sleep(millisUnit);

}catch(InterruptedException e) {

e.printStackTrace();

}

}

},"join-" +i);

tmp.start();

tmp.join();//不停地监测线程是否执行完成,执行完成才继续往下

}return System.currentTimeMillis() -startMillis;

}/** CountdownLatch可同时阻塞多个线程,但它们可并发执行*/

public long preserveOrderViaCountdownLatch() throwsInterruptedException {long startMillis =System.currentTimeMillis();final CountDownLatch countDownLatch = newCountDownLatch(count);for (int i = 0; i < count; i++) {new Thread(newRunnable() {

@Overridepublic voidrun() {try{

Thread.sleep(millisUnit);

}catch(InterruptedException e) {

e.printStackTrace();

}//只要计数器清零,等待的线程就可以开始执行,于是可以达到并发的效果

countDownLatch.countDown();

}

},"countDownLatch-" +i).start();

}

countDownLatch.await();return System.currentTimeMillis() -startMillis;

}

}

@Testpublic void testPreserveOrderViaJoin() throwsInterruptedException {

ThreadOrder threadOrder= newThreadOrder();

Assert.assertEquals(count, threadOrder.preserveOrderViaJoin()/millisUnit);

}

@Testpublic void testPreserveOrderViaCountdownLatch() throwsInterruptedException {

ThreadOrder threadOrder= newThreadOrder();

Assert.assertEquals(1, threadOrder.preserveOrderViaCountdownLatch() /millisUnit);

}

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。