thrack
全部博文(34)
2013年(2)
2011年(15)
2010年(3)
2009年(2)
2008年(3)
2007年(9)
汉唐归来
yxsdawn
73128175
guofzhao
wzengzhi
zhangbon
wolfgrou
canigree
mj133233
分类: Java
2008-12-12 11:45:52
import java.util.concurrent.CountDownLatch; public class TestThread { static int cnt = 100; static int last = -1; static int type = 2; static int liveCnt = cnt; static CountDownLatch counter = new CountDownLatch(cnt); static class WorkThread extends Thread { Object lock = null; int id = -1; int sleep = -1; WorkThread(int id, Object lock) { this.id = id; this.lock = lock; } public void run() { try { work(); } catch (Exception e) { } synchronized (lock) { //System.out.println("thread " + id + " done"); last = sleep; liveCnt--; counter.countDown(); lock.notify(); } } private void work() { try { sleep = (int) (Math.random() * 1000 * 10); //System.out.println("thread " + id + " sleep=" + sleep); Thread.sleep(sleep); } catch (InterruptedException e) { } } } /** * @param args */ public static void main(String[] args) { String lock = "lock"; long start = System.currentTimeMillis(); WorkThread[] workers = new WorkThread[cnt]; for (int i = 0; i < cnt; i++) { workers[i] = new WorkThread(i, lock); workers[i].start(); } switch (type) { //join 方式 case 1 : for (Thread worker : workers) { try { worker.join(); } catch (InterruptedException e) { } } break; //wait - notify 方式 case 2 : while (true) { synchronized (lock) { if (liveCnt == 0) break; try { lock.wait(); } catch (InterruptedException e) { } } } //CountDownLatch 方式 case 3 : try { counter.await(); } catch (InterruptedException e) { } break; } long end = System.currentTimeMillis(); System.out.println("type=" + type); System.out.println("All done, elapse: " + (end - start)); System.out.println("last=" + last); System.out.println("delay=" + (end - start - last)); } }
上一篇:ulimit 问题
下一篇:ld.so.conf 文件与PKG_CONFIG_PATH变量<转>
登录 注册