使用相同的可运行实例初始化两个线程 [英] Initializing two threads with the same instance of a runnable
问题描述
用同一个可运行实例初始化两个线程是不是很糟糕?使用单独的可运行实例进行初始化会有什么区别,并且为同一个可运行实例共享内存位置与性能有什么关系?
Is it bad programming to initialize two threads with the same instance of a runnable? What difference would it make to initialize with separate instances of a runnable, and does sharing memory locations at all for the same instance of a runnable have anything to do with performance?
public static void main(String[] args)throws Exception {
H h = new H();
H h2 = new H();
Thread j = new Thread(h);
j.setName("11");
Thread jj = new Thread(h);//instead of new H()
jj.setName("22");
j.start();
jj.start();
}
class H implements Runnable {
public void run() {
while(true) {
System.out.println(Thread.currentThread().getName());
}
}
}
推荐答案
只要您正在运行的代码旨在支持这一点,这样做绝对没问题.它不仅可以通过使用单个实例而不是多个实例来节省一些内存,而且如果这些线程尝试通过共享数据进行通信,那么它可能是绝对需要的!
It's absolutely fine to do it so long as the code you're running is designed to support that. Not only will it save some memory by having a single instance instead of multiple instances, but if those threads are trying to communicate via shared data, then it may be absolutely required!
诚然,通过共享状态进行通信是线程经常变得棘手的地方,所以这需要小心完成,但从线程系统本身的角度来看,让两个线程调用 run<绝对没有问题/code> 单个
Runnable
实例的方法.
Admittedly communicating via shared state is where threading often gets tricky, so this needs to be done carefully, but from the point of view of the threading system itself, there's absolutely no problem in having two threads call the run
method of a single Runnable
instance.
这篇关于使用相同的可运行实例初始化两个线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!