使用同一个runnable实例初始化两个线程 [英] Initializing two threads with the same instance of a runnable
问题描述
使用同一个runnable实例初始化两个线程是不好的编程吗?使用单独的runnable实例初始化它们有什么区别,并且对于同一个runnable实例共享内存位置与性能有什么关系?
public static void main(String [] args)throws Exception {
H h = new H();
H h2 = new H();
线程j =新线程(h);
j.setName(11);
线程jj =新线程(h); //而不是新的H()
jj.setName(22);
j.start();
jj.start();
}
类H实现Runnable {
public void run(){
while(true){
System.out.println ().getName());
}
}
}
只要你运行的代码被设计来支持它,这是绝对可行的。不仅通过单个实例而不是多个实例来保存一些内存,而且如果这些线程试图通过共享数据进行通信,那么它可能是绝对必要的!
诚然,通过共享状态进行通信是线程通常很棘手的地方,所以这需要仔细地做,但是从线程系统本身的角度来看,有两个线程调用单个
方法。 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!
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.
这篇关于使用同一个runnable实例初始化两个线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!