java - 多线程实例化一次 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();
}
我的意思是新的一次与新的每个线程?
解决方案
这是两者之间的区别:
在您的第一个示例中,您只创建一个ThreadImpl
实例,因此也只Worker
创建一个AnotherWorker
实例。这将在您创建的不同线程之间共享。
在您的第二个示例中,您正在为每个示例创建一个,Thread
这可能应该是首选方式,除非您有理由共享Worker
对象。
推荐阅读
- react-native - 如何从反应本机应用程序重新启动android设备
- python-3.x - PYTHON:如果对象是字典中的键,如何访问类对象的成员
- r - 用 group by 计算 r 中一列中唯一字符串的数量
- flutter - Flutter 错误:任务 ':app:compileFlutterBuildDebug 执行失败
- c++ - 在这些直接在函数中使用参数的情况下,我是否需要完善前向参数?
- mongodb - 在 mongodb 中如何按天聚合数据并以日期格式存储聚合日期
- c++ - std::make_unique 中的完美转发
> 不太完美 - android - ImageView 无法使用 SimpleAdapter 显示图像
- spring - Spring Boot 过滤器中的模拟 Rest API 调用
- angular - ng snotify 登录后不显示烤面包机