当前位置: 代码迷 >> 综合 >> 1. CountDownLatch
  详细解决方案

1. CountDownLatch

热度:46   发布时间:2024-01-28 23:52:42.0
【【【【【CountDownLatchTest1】】】】】
package countdownlatch;import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;public class CountDownLatchTest1 {private static final ExecutorService executor = Executors.newFixedThreadPool(2);private static final CountDownLatch latch = new CountDownLatch(10);public static void main(String[] args) throws InterruptedException {// 1. 获取数据int[] data = getDate();// 2. 多线程对数据进行处理for (int i = 0; i < data.length; i++) {executor.submit(new SimpleRunnable(data, i, latch));}// 3. 所有线程都处理完成后,再将处理后的数据保存latch.await();executor.shutdown();System.out.println("all task is finish.");}public static class SimpleRunnable implements Runnable {private int[] data;private int index;private CountDownLatch latch;public SimpleRunnable(int[] data, int index, CountDownLatch latch) {this.data = data;this.index = index;this.latch = latch;}@Overridepublic void run() {if (index % 2 == 0) {data[index] = data[index] * 2;} else {data[index] = data[index] * 3;}try {TimeUnit.SECONDS.sleep(3);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(Thread.currentThread().getName() + " ---> task - " + index + " is finish.");latch.countDown();}}public static int[] getDate() {return new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};}
}

 

【【【【【【【CountDownLatchTest2】】】】】

package countdownlatch;import com.hikvision.fdrc.common.util.TimeUtil;import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;public class CountDownLatchTest2 {public static void main(String[] args) throws InterruptedException {CountDownLatch latch = new CountDownLatch(1);new Thread(new Runnable() {@Overridepublic void run() {System.out.println(Thread.currentThread().getName() + " init is working");try {TimeUnit.SECONDS.sleep(3);latch.await();} catch (InterruptedException e) {e.printStackTrace();}System.out.println(Thread.currentThread().getName() + " init is done");}}, "T-init").start();new Thread(new Runnable() {@Overridepublic void run() {System.out.println("other init is working");try {TimeUnit.SECONDS.sleep(5);} catch (InterruptedException e) {e.printStackTrace();} finally {latch.countDown();}System.out.println("other init is done");}}, "T-other").start();//        Thread.currentThread().join();}
}