java循环屏障,循环屏障Java,如何验证?

我正在准备采访,只是想准备一些基本的线程示例和结构,以便我可以在白板编码期间使用它们,如果必须的话.

我正在阅读有关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个语句,然后是“release.hurray”语句的’outburst’.但无论我选择什么样的睡眠,我都会看到所有声明的爆发.

我在这里错过了什么吗?

谢谢

P.S:有没有像http://codepad.org/F01xIhLl这样的在线编辑器,我只需要放入Java代码并点击按钮即可运行丢弃的代码? .我发现一些需要一些配置才能运行任何代码.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值