简体   繁体   English

通过传递Runnable的相同实例来创建两个线程

[英]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.

相关问题 使用可运行对象的相同实例初始化两个线程 - Initializing two threads with the same instance of a runnable 两个线程作用于同一个runnable - two threads acting on the same runnable 如何在不同的线程中执行两种接受相同 class 的可运行实例的方法? - How to execute two methods accepting runnable instance of same class in different threads? 创建多线程并实例化可运行 - Creating multi threads and instantiating runnable 使用Runnable VS的单个实例创建多个线程。 每个线程都有单独的实例 - Creating multiple threads with a single instance of Runnable VS. with separate instances for each thread 如何对两个不同的线程使用CountDownLatch,每个线程都有相同的可运行类 - How to use the CountDownLatch for two different threads each of them has the same runnable class 两个线程进入可运行的同步方法 - Two threads entering synchronized methods of runnable Seam Hibernate将相同的EntityManger实例提供给两个单独的线程 - Seam Hibernate Serves same EntityManger instance to two separate threads 使用相同和不同类实例的两个线程之间的同步? - Synchronization between two threads using same and different instance of class? “Runnable :: run” - 这是如何创建Executor实例的? - “Runnable::run” - How is this creating an Executor instance?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM