【发布时间】:2018-04-25 14:29:40
【问题描述】:
我正在尝试使用自定义对象创建一个新线程,然后从主线程调用此自定义对象方法。这个想法是主线程可以继续做其他事情,而自定义对象继续在第二个线程中工作:
public class Multithreading {
public static void main(String[] args) {
Multithreading mt = new Multithreading();
mt.multiTest();
}
public void multiTest() {
SomeObject someObject = new SomeObject();
Thread thread = new Thread(someObject);
thread.setDaemon(true);
thread.start();
someObject.startit();
int i = 0;
while (i < 3) {
try {
System.out.println("this is the main thread being busy");
Thread.sleep(3000);
i += 1;
} catch (InterruptedException e) {
}
}
}
class SomeObject implements Runnable {
public void sayHello() {
System.out.println("this is the second thread being busy");
}
public void startit() {
int i = 0;
while (i < 3) {
try {
sayHello();
Thread.sleep(3000);
i += 1;
} catch (InterruptedException e) {
}
}
}
@Override
public void run() {
// TODO Auto-generated method stub
}
}
}
输出是:
this is the second thread being busy
this is the second thread being busy
this is the second thread being busy
this is the main thread being busy
this is the main thread being busy
this is the main thread being busy
应该更像这样:
this is the second thread being busy
this is the main thread being busy
this is the second thread being busy
this is the main thread being busy
this is the second thread being busy
this is the main thread being busy
所以主线程被阻塞,直到方法完成。主线程是否在第二个线程中等待 someObject.startit() 的完成(作为返回类型为 void,我认为情况并非如此)?还是在第一个线程中执行,因此阻塞了它?
我知道使用下面的代码我可以在另一个线程中执行someObject.startit(),但它每次都会从头开始创建,我无法承受线程创建开销:
new Thread(() -> {someObject.startit();}).start();
一个线程如何在不阻塞的情况下调用另一个线程中的对象的方法?
【问题讨论】:
-
每次需要运行一个单独的线程时,都需要创建一个新的线程对象。没有办法避免这种开销。您不能重用线程对象。最重要的是,您似乎有一个误解,即一旦将对象放入线程并启动线程,该对象中的任何操作都由该线程运行。这不是真的。
标签: java multithreading