zoukankan      html  css  js  c++  java
  • 线程交互

    1. import java.util.concurrent.CountDownLatch;  
    2.   
    3. public class LatchDriverDemo {  
    4.    private static final  int N = 5;  
    5.    public static void main(String[] args) throws InterruptedException {  
    6.     // 用于向工作线程发送启动信号  
    7.        CountDownLatch startSignal = new CountDownLatch(1);  
    8.     // 用于等待工作线程的结束信号 CountDownLatch  
    9.        CountDownLatch doneSignal = new CountDownLatch(N);  
    10.        for (int i = 0; i < N; i++)   
    11.         // 创建启动线程  
    12.         new Thread(new LatchWorker(startSignal,doneSignal),"t"+i).start();  
    13.         // 得到线程开始工作的时间  
    14.         long start = System.currentTimeMillis();  
    15.         //主线程,递减开始计数,让所有线程开始工作  
    16.         startSignal.countDown();  
    17.         //主线程开始阻塞,等待其他线程完成  
    18.         startSignal.await();  
    19.         long end = System.currentTimeMillis();  
    20.           
    21.         //System.out.println("All Work Take Time : "+ (end - start)/1000.0+"s" );  
    22.         System.out.println(end+"   "+start);  
    23.    }  
    24. }  
    25.   
    26. import java.util.concurrent.CountDownLatch;  
    27.   
    28. public class LatchWorker implements Runnable{  
    29.     private final CountDownLatch startSignal;  
    30.     private final CountDownLatch doneSignal;  
    31.     public LatchWorker(CountDownLatch startSignal,CountDownLatch doneSignal){  
    32.         super();  
    33.         this.startSignal = startSignal;  
    34.         this.doneSignal = doneSignal;  
    35.     }  
    36.     @Override  
    37.     public void run() {  
    38.          try {  
    39.             startSignal.await();  
    40.             dowork();  
    41.             doneSignal.countDown();  
    42.         } catch (InterruptedException e) {  
    43.             e.printStackTrace();  
    44.         }  
    45.           
    46.     }  
    47.     private void dowork() {  
    48.         // TODO Auto-generated method stub  
    49.         int a = 0 ;  
    50.         for (int i = 0; i < 10000; i++) {  
    51.             a += 1;  
    52.         }  
    53.         System.out.println(Thread.currentThread().getName()+"="+a);  
    54.     }  
    55.      
    56. }  
  • 相关阅读:
    数组的拼接
    numpy的切片和索引
    细说python中的round()方法
    Numpy数组的创建
    快排 [随机数]
    对于归并排序递归的理解
    A1044 Shopping in Mars [连续子序列分割]
    A1085 Perfect Sequence [二分、two pointers]
    快速幂
    [转] 二分法求外接圆最大半径
  • 原文地址:https://www.cnblogs.com/hold/p/3097083.html
Copyright © 2011-2022 走看看