我正在准备面试,只想准备一些基本的线程示例和结构,以便在必要时可以在我的白板编码中使用它们。
我正在阅读关于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;
}您可以按原样复制、粘贴,然后在编译器中运行。
我想要验证的是,所有线程在代码中确实都在等待:
barrier.await();我等待了一段时间,希望能看到控制台上依次出现4条语句,然后是"released..hurray“语句的”爆发“。但是,无论我选择什么作为睡眠,我都会看到所有语句一起爆发。
我是不是漏掉了什么?
谢谢,附言:有没有像http://codepad.org/F01xIhLl这样的在线编辑器,我可以把Java代码放进去,然后点击一个按钮就可以运行一段丢弃的代码?我发现了一些需要一些配置才能运行任何代码的代码。
发布于 2011-05-22 06:07:08
代码看起来不错,但在休眠之前写入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);在我的机器上,我仍然看到一个突发,但很明显线程在屏障上被阻塞了。
发布于 2011-05-22 06:11:44
如果你想避免第一次突发,在睡眠中使用一个随机的
Thread.sleep(1000*(int)(8*Math.rand()));发布于 2011-05-22 06:17:31
我做了一些等待,希望看到控制台上依次出现4条语句,后面是"released..hurray“语句的”
“。但是,无论我选择什么作为睡眠,我都会看到所有语句一起爆发。
我观察到的行为是,所有创建的线程都会休眠大约相同的时间。请记住,其他线程可以在过渡期间执行它们的工作,因此将被调度;由于所有线程创建休眠的时间相同,因此调用System.out.println调用的时刻之间的差别很小。
编辑:other answer of sleeping of a random amount of time将有助于更好地理解屏障的概念,因为它将保证(在某种程度上)多个线程在不同时刻到达屏障的可能性。
https://stackoverflow.com/questions/6084706
复制相似问题