到目前为止,我已经避免了测试多线程代码的噩梦,因为它看起来像是一个雷区太多了.我想问一下人们如何测试依赖线程成功执行的代码,或者人们如何测试那些只在两个线程以给定方式交互时出现的问题?
对于今天的程序员来说,这似乎是一个非常关键的问题,将我们的知识集中在这个imho上是有用的.
是否有任何测试多线程代码的指导原则(除了在问题上抛出一堆线程并交叉手指).
我基本上正在寻找测试数据损坏,死锁和其他并发问题的好方法.基本上我希望能够通过测试证明代码是线程安全的.
Java中是否有任何框架可以让您轻松编写多线程场景的测试?
我必须使用锁作为我课程工作的一部分来实现自定义障碍类.为了测试我的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);
}
} …Run Code Online (Sandbox Code Playgroud)