相关疑难解决方法(0)

使用runnable的相同实例初始化两个线程

使用相同的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)

java concurrency

19
推荐指数
3
解决办法
2万
查看次数

关于多个胎面上的相同Runnable参考

当我们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)

java multithreading

1
推荐指数
1
解决办法
195
查看次数

标签 统计

java ×2

concurrency ×1

multithreading ×1