使用相同的runnable实例初始化两个线程是不是很糟糕的编程?使用runnable的单独实例进行初始化会有什么不同,并且对于runnable的同一实例共享内存位置与性能有什么关系?
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());
}
}
}
Run Code Online (Sandbox Code Playgroud) 当我们start()通过传递一个Runnable对象作为参数调用一个Thread时,我们可以传递相同的Runnable引用来启动多个线程吗?
public class MyMain {
public static void main(String[] args) {
MyRunnableImpl impl = new MyRunnableImpl();
new Thread(impl).start();
new Thread(impl).start();
}
}
Run Code Online (Sandbox Code Playgroud)