Java 线程赢得';别忘了点火
因此,我试图让许多线程在不干预java的情况下自行启动和运行 线程是通过扩展thread类生成的,如下所示:Java 线程赢得';别忘了点火,java,multithreading,Java,Multithreading,因此,我试图让许多线程在不干预java的情况下自行启动和运行 线程是通过扩展thread类生成的,如下所示: public class MyThread extends Thread{ public void run(){ executeEvents(); } executeEvents内部有一组业务逻辑 然而,在这被称为之前,螺纹是这样制作的: public MyThread(int threadNumber, ArrayList<Event> events, Mailb
public class MyThread extends Thread{
public void run(){
executeEvents();
}
executeEvents内部有一组业务逻辑
然而,在这被称为之前,螺纹是这样制作的:
public MyThread(int threadNumber, ArrayList<Event> events, Mailbox mailbox){
this.events = events;
this.mailbox = mailbox;
this.threadNumber = threadNumber;
}
(这在事件
类中)
因此,它们不应该按顺序完成。您应该使用该方法,而不是Thread\run()
。后者不会生成要并行运行的线程:
for(int i = 0; i < threads.length; i++){
threads[i] = new Thread(new MyThread(i,eventsForThread[i],mailbox));
threads[i].start();
}
方法start()
将生成一个新线程,但在这之后,您立即调用threads[i].executeEvents()
,它将阻塞直到返回。这不是应该如何实施的。start
方法已经调用了MyThread
的run
方法,该方法依次调用executeEvents
。您只需调用start
。将事件“添加”到线程的部分应该在调用之前,类似于:
for(int i = 0; i < threads.length; i++){
threads[i] = new MyThread();
threads[i].addToMyThread(i,eventsForThread[i],mailbox);
threads[i].start(); // this will call executeEvents in a separate thread
}
for(int i=0;i
当我这样做的时候,对于单个线程,在那之后似乎什么都没有发生,而且我之前得到的输出现在都没有显示出来。所以请注意,MyThread
被用作另一个实际启动的线程的Runnable
。@user1742032你确定吗?您是否尝试调试spawnThreads
方法?或者添加一些日志来跟踪它的执行?@manouti我很确定它是以串联方式执行的,因为执行的部分业务逻辑包括大约300ms+多次的休眠(并且是随机的),这意味着不可能每次运行时线程都按顺序完成。我还尝试将类的构造函数更改为空,运行start,然后输入需要添加到每个线程中的变量,但之后任何事件调用都无法满足parallel@user1742032我认为你应该在问题中发布这些信息。
for(int i = 0; i < threads.length; i++){
threads[i] = new Thread(new MyThread(i,eventsForThread[i],mailbox));
threads[i].start();
}
for(int i = 0; i < threads.length; i++){
threads[i] = new MyThread();
threads[i].start();
threads[i].addToMyThread(i,eventsForThread[i],mailbox);
threads[i].executeEvents(); // this is causing the serial execution
}
for(int i = 0; i < threads.length; i++){
threads[i] = new MyThread();
threads[i].addToMyThread(i,eventsForThread[i],mailbox);
threads[i].start(); // this will call executeEvents in a separate thread
}