尽管你的问题表明你有很好的机会找到更好的程序设计,但如果你确实需要这样的功能,你可以通过ThreadPoolExecutor
用一个线程来实现它。只需将您的方法method1()
和method2()
分别包含在两个不同的Callable
中,然后将它们提交给您的单线程池。
class Method1Task implements Callable<Void> {
public Void call() throws Exception {
// method 1 body here
return null;
}
}
class Method2Task implements Callable<Void> {
public Void call() throws Exception {
// method 2 body here
return null;
}
}
...
// Create a single-thread pool and use it to submit tasks
private final ExecutorService executor = Executors.newFixedThreadPool(1);
void method1() {
executor.submit(new Method1Task());
}
void method2() {
executor.submit(new Method2Task());
}
如果您需要等待方法完井,使用由submit()
小号返回Future
秒。如果您需要从方法返回值,请更改Void
以获取适当的数据类型。
在Java 8它更简单,你不需要Callable
S:
executor.submit(() -> {
// call the method you need here
});
基于该帖的答案是一个坚定的没有。 – biziclop
为什么你认为你需要他们在同一个线程中运行? – Kayaman
@Kayaman在'method1'中,我使用了'writeLock.lock()',并且我想使用'method2'中的'writeLock.unlock()'来解锁它。这里,'writeLock'是一个'ReentrantReadWriteLock'。 – hengxin