Java 如何在测试仪中连接两个线程类?
我有两个线程类。在测试程序中,我需要声明和创建两个线程对象,它们分别属于buyThread和sellThread,并运行和连接线程Java 如何在测试仪中连接两个线程类?,java,multithreading,Java,Multithreading,我有两个线程类。在测试程序中,我需要声明和创建两个线程对象,它们分别属于buyThread和sellThread,并运行和连接线程 Thread bt[] = new Thread[2]; // declare and create 2 threads object Thread st[] = new Thread[2]; // declare and create 2 threads object for (int i = 0; i < 2; i++) {
Thread bt[] = new Thread[2]; // declare and create 2 threads object
Thread st[] = new Thread[2]; // declare and create 2 threads object
for (int i = 0; i < 2; i++) {
bt[i] = new BuyThread(rand1, rand2, stock);
bt[i].start();
}
for (int i = 0; i < 2; i++) {
st[i] = new SellThread(rand1, rand2, stock);
st[i].start();
}
for (int i = 0; i < 2; i++) // Can I do it this way for each Thread ?
{
try {
bt[i].join();
} catch (InterruptedException e) {
}
}
for (int i = 0; i < 2; i++) {
try {
st[i].join();
} catch (InterruptedException e) {
}
}
threadbt[]=新线程[2];//声明并创建2线程对象
线程st[]=新线程[2];//声明并创建2线程对象
对于(int i=0;i<2;i++){
bt[i]=新的购买线程(rand1,rand2,股票);
bt[i].start();
}
对于(int i=0;i<2;i++){
st[i]=新的销售线索(rand1,rand2,股票);
st[i].start();
}
for(inti=0;i<2;i++)//我可以用这种方式为每个线程执行此操作吗?
{
试一试{
bt[i].join();
}捕捉(中断异常e){
}
}
对于(int i=0;i<2;i++){
试一试{
st[i].join();
}捕捉(中断异常e){
}
}
您的加入很好
请注意,您首先等待两个BuyThread
实例完成,然后等待两个SellThread
实例完成(按该顺序)
将所有内容压缩到一个数组中的好处是,您只需将每个Buy
/Sell
线程类的新实例添加到数组中,您的应用程序将等待它们全部完成
这不是你想要的吗
Edit:如注释中所述,您应该实现runnable,而不是扩展
线程
类。那更干净。有关详细信息,请参阅。问题是什么?您仍然声明了4个线程(但没有启动任何线程)--ook,您编辑了问题,但问题仍然是什么。join方法将让主线程等待所有线程完成。我可以检查这是写入join()的正确方法吗?我可以只为(int I=0;I<2;I++){try{st[I].join();bt[I]}catch(InterruptedException e)进行写入吗{}好的,您已经知道要连接的线程是什么(0,1),所以您可以只执行st[0].join();st[1]。join();避免这样做到底是什么问题?作为补充说明,我建议使用,而不是使用来管理您的任务…非常感谢,我将从这里继续。