[英]Creating Two Threads by passing the same instance of Runnable
Thread runnableInst = new Runnable(){ public void run(){}};
Thread thread1 = new Thread(runnableInst);
Thread thread2 = new Thread(runnableInst);
thread1.start();
thread2.start();
Is it fine to start two thread on the same Object runnableInst ? 在同一个Object runnableInst上启动两个线程可以吗?
Is it good to make this kind of design? 做这种设计好吗?
Yes, you can do this but one thing to watch is that both threads will be accessing the instance data of the runnableInst
. 是的,您可以这样做,但有一点需要注意的是两个线程都将访问
runnableInst
的实例数据。 So you will have to make sure that access is synchronised where necessary. 因此,您必须确保在必要时同步访问。
There's no problem with doing that. 这样做没有问题。 However, if you plan on dispatching a lot of parallel tasks, you might want to start using the
ExecutorService
API. 但是,如果您计划分派大量并行任务,则可能需要开始使用
ExecutorService
API。
It is indeed possible. 这确实是可能的。 I don't think it is fine or good design in most situations.
在大多数情况下,我不认为这是好的或好的设计。 I like to consider a Runnable instance to be an isolated piece of code that only shares data with other threads through well-defined, safe ways.
我喜欢将Runnable实例视为一段孤立的代码,它只通过明确定义的安全方式与其他线程共享数据。
Is it fine to start two thread on the same Object runnableInst ? 在同一个Object runnableInst上启动两个线程可以吗?
Yes, it is fine to start two threads on the same Object runnableInst. 是的,可以在同一个Object runnableInst上启动两个线程。
Is it good to make this kind of design -- it depends on the use case. 做这种设计是好事 - 这取决于用例。 For example, if there is nothing related to a read/write on a shared resource, then this is a good design.
例如,如果没有与共享资源上的读/写相关的内容,那么这是一个很好的设计。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.