cod*_*ver 5 java concurrency multithreading
我正在准备采访,只是想准备一些基本的线程示例和结构,以便我可以在白板编码期间使用它们,如果必须的话.
我正在阅读有关CyclicBarrier的文章,并且只是在尝试它,所以我写了一个非常简单的代码:
import java.util.concurrent.CyclicBarrier;
public class Threads
{
/**
* @param args
*/
public static void main(String[] args)
{
// ******************************************************************
// Using CyclicBarrier to make all threads wait at a point until all
// threads reach there
// ******************************************************************
barrier = new CyclicBarrier(N);
for (int i = 0; i < N; ++i)
{
new Thread(new CyclicBarrierWorker()).start();
}
// ******************************************************************
}
static class CyclicBarrierWorker implements Runnable
{
public void run()
{
try
{
long id = Thread.currentThread().getId();
System.out.println("I am thread " + id + " and I am waiting for my friends to arrive");
// Do Something in the Thread
Thread.sleep(1000*(int)(4*Math.random()*10));
// Now Wait till all the thread reaches this point
barrier.await();
}
catch (Exception e)
{
e.printStackTrace();
}
//Now do whatever else after all threads are released
long id1 = Thread.currentThread().getId();
System.out.println("Thread:"+id1+" We all got released ..hurray!!");
System.out.println("We all got released ..hurray!!");
}
}
final static int N = 4;
static CyclicBarrier barrier = null;
}
Run Code Online (Sandbox Code Playgroud)
您可以按原样复制粘贴并在编译器中运行.
我想验证的是,确实所有线程在代码中等待此时:
barrier.await();
Run Code Online (Sandbox Code Playgroud)
我放了一些等待,并希望我会在控制台上以顺序的方式一个接一个地看到4个语句,然后是"release.hurray"语句的'outburst'.但无论我选择什么样的睡眠,我都会看到所有声明的爆发.
我在这里错过了什么吗?
谢谢PS:有没有像http://codepad.org/F01xIhLl这样的在线编辑器,我可以放置Java代码并点击按钮来运行丢弃代码?.我发现一些需要一些配置才能运行任何代码.
代码看起来不错,但在睡眠之前写入 System.out 可能更具启发性。在 run() 中考虑这一点:
long id = Thread.currentThread().getId();
System.out.println("I am thread " + id + " and I am waiting for my friends to arrive");
// Do Something in the Thread
Thread.sleep(1000*8);
Run Code Online (Sandbox Code Playgroud)
在我的机器上,我仍然看到突发,但很明显线程被阻塞在屏障上。
| 归档时间: |
|
| 查看次数: |
1291 次 |
| 最近记录: |