技术开发 频道

Junit多线程测试的一个解决方案

  【IT168 技术文档】看到的一个解决方法,代码如下:

  public class MyThreadTest {

  final static private long THREAD_MAX_RUNTIME = 1000;

  final static private long THREAD_WAITTIME = 200;

  private MyThread myThread1 = null;

  private MyThread myThread2 = null;

  @Before

  public void setUp() throws Exception {

  myThread1 = new MyThread();

  myThread2 = new MyThread();

  }

  @Test(timeout = THREAD_MAX_RUNTIME)

  public void testRun() throws Exception {

  Thread t1 = new Thread(myThread1);

  Thread t2 = new Thread(myThread2);

  t1.start();

  t2.start();

  Thread tc = Thread.currentThread();

  synchronized (tc) {

  while (t1.isAlive() || t2.isAlive()) {

  tc.wait(THREAD_WAITTIME);

  }

  tc.notify();

  }

  Assert.assertEquals(100, myThread1.getI());

  Assert.assertEquals(100, myThread2.getI());

  }

  }

  另外我发现,当使用二级缓存时,Hibernate的load方法是不会抛出乐观锁错误,因为load返回的只是一个代理,等到真正要使用的时候,他才去缓存中拿,而且拿到的一定是最新的状态!

0
相关文章