【发布时间】:2018-10-03 15:51:09
【问题描述】:
我想为我的一个项目测试多线程,同时尝试开发一个解决方案,以防出现问题。
所以我做了这个小测试:
主要
public class main
{
static int addToCounter;
static int addToErrorCounter;
public static void main(String[] args) throws InterruptedException
{
int threads = 10;
Executor exec = new Executor();
for (int i = 0; i < threads; i++)
{
double error = Math.random();
testClass aldo = new testClass();
Thread thread = aldo.getThread(300, error);
exec.execute(thread);
}
while (threads != (addToCounter + addToErrorCounter))
{
System.out.println("Not all threads finished, number of finished threads is: " + (addToCounter + addToErrorCounter));
Thread.sleep(50);
}
System.out.println("Number of Threads that finished correctly: " + addToCounter);
}
}
测试类
import test1.main;
public class testClass
{
public Thread getThread(long time, double error)
{
Thread thread = new Thread()
{
public void run()
{
try
{
Thread.sleep(time);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
if (error > 0.5)
{
main.addToErrorCounter++;
throw new java.lang.Error("HELLO");
}
System.out.println("I DID THIS!");
main.addToCounter++;
}
};
return thread;
}
}
(您必须修复导入,我也使用自定义类 Executor,尽管这只是 ExecutorService 的包装)
奇怪的行为是有时它可以正常工作,有时却不能(总终止线程数为 9,尽管我可以清楚地看到它打印了“我做到了!”并且错误正好 10 次)。
有什么办法吗?
【问题讨论】:
-
@Downvoter,想知道为什么投反对票?
-
你为什么不让每个线程也说出它的名字,这样你就可以跟上哪个线程正在开始/结束,以及将线程数减少到 5 以帮助降低线程数故障排除?
-
你说它的名字是什么意思?线程都使用相同的类,唯一的“移动”部分是
Math.random()。我不明白这个名字在这里会有什么帮助。 -
What does your step debugger tell you? 这很容易理解,只需通过一步调试器即可。
-
Jarrod,这个问题与您列出的任何一个问题的 重复 有什么关系?当然,第一个是相关的,但是刚开始使用多线程 java 的初级程序员不太可能将该行识别为问题代码,然后考虑围绕原子性进行搜索。考虑到他们明显的技能水平,我觉得你给 OP 带来了过度的困难。
标签: java multithreading