首页 > 解决方案 > 多线程实例化一次 vs 每个线程

问题描述

有这个类:

public class ThreadImpl implements Runnable {

 public ThreadImpl(Worker worker, AnotherWorker anotherWorker){
     this.worker = worker;
     this.anotherWorker = anotherWorker;
 }


private Worker worker;

private AnotherWorker anotherWorker;

public void run(){
 ...
 worker.doThis();
 ...
 anotherWorker.doThat();
 ...
 }
 }

这些之间有什么区别(首选哪一个以及为什么?):

1.

ThreadImpl threadImpl = new ThreadImpl(new Worker(), new AnotherWorker());
for(int i=0; i < 5; i++) {
     new Thread(threadImpl).start();
}

2.

for(int i=0; i < 5; i++) {
    ThreadImpl threadImpl = new ThreadImpl(new Worker(), new AnotherWorker());
    new Thread(threadImpl).start();
}

我的意思是新的一次与新的每个线程?

标签: javamultithreading

解决方案


这是两者之间的区别:

在您的第一个示例中,您只创建一个ThreadImpl实例,因此也只Worker创建一个AnotherWorker实例。这将在您创建的不同线程之间共享。

在您的第二个示例中,您正在为每个示例创建一个,Thread这可能应该是首选方式,除非您有理由共享Worker对象。


推荐阅读