I had to do an implementation of a custom barrier class using locks as part of my course work.
To test my LockBarrier
class, I came up with a the following test code. It is working correctly, but I am concerned whether that is the proper way to do. Could you please suggest improvements I can do, especially structuring the classes. I think my way of coding is not the correct one. Any suggestions are welcome.
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();
}
}
See Question&Answers more detail:os