【发布时间】:2011-05-24 00:48:30
【问题描述】:
在我的课程作业中,我必须使用锁来实现自定义屏障类。
为了测试我的LockBarrier 类,我想出了以下测试代码。它工作正常,但我担心这是否是正确的做法。您能否建议我可以做的改进,特别是构建课程。我认为我的编码方式不正确。欢迎提出任何建议。
public class TestDriver
{
private static LockBarrier barrier;
static class Runnable1 implements Runnable
{
public Runnable1()
{ }
public void run()
{
try
{
System.out.println(Thread.currentThread().getId()+" lazy arrived at barrier");
Thread.sleep(10000);
barrier.await();
System.out.println(Thread.currentThread().getId()+" passed barrier");
}
catch (InterruptedException ie)
{
System.out.println(ie);
}
}
}
static class Runnable2 implements Runnable
{
public Runnable2()
{ }
public void run()
{
try
{
System.out.println(Thread.currentThread().getId()+" quick arrived at barrier");
//barrier.await(1,TimeUnit.SECONDS);
barrier.await();
System.out.println(Thread.currentThread().getId()+" passed barrier");
}
catch (InterruptedException ie)
{
System.out.println(ie);
}
}
}
static class Runnable3 implements Runnable
{
public Runnable3()
{ }
public void run()
{
try
{
System.out.println(Thread.currentThread().getId()+" very lazy arrived at barrier");
Thread.sleep(20000);
barrier.await();
System.out.println(Thread.currentThread().getId()+" passed barrier");
}
catch (InterruptedException ie)
{
System.out.println(ie);
}
}
}
public static void main(String[] args) throws InterruptedException
{
barrier = new LockBarrier(3);
Thread t1 = new Thread(new TestDriver.Runnable1());
Thread t2 = new Thread(new TestDriver.Runnable2());
Thread t3 = new Thread(new TestDriver.Runnable3());
t1.start();
t2.start();
t3.start();
t1.join();
t2.join();
t3.join();
}
}
【问题讨论】:
-
它相当冗长,但是,我唯一希望看到的是通知 LockBarrier 以允许另一个线程继续进行的东西。如果您正在执行类似内置 Condition 类的操作,您可能希望看到一个被调用的 signal()。
-
signalAll() 在 LockBarrier 的 await() 实现中完成。当所有线程都到达屏障时,signalAll 我们完成了。你有什么建议让它不那么冗长?
-
我的回答如何?有用吗?
标签: java multithreading