- 论坛徽章:
- 0
|
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 = new WorkThread(i, lock);
workers.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));
}
}
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/17518/showart_1715528.html |
|