[英]thread of different class object in java
I have 2 java class "LegacyDAO" and "NewDAO" implementing Runnable. 我有2个Java类“ LegacyDAO”和“ NewDAO”实现了Runnable。 In an another class "Test" we create one object of each LegacyDAOObj and NewDAOObj.
在另一类“测试”中,我们为每个LegacyDAOObj和NewDAOObj创建一个对象。
Class Test {
public static void main(String args[]) {
LegacyDAO legacyDAOObj= new LegacyDAO();
NewDAO newDAOObj= new NewDAO();
Thread legacyDBThread= new Thread(legacyDAOObj);
Thread newDBThread= new Thread(newDAOObj);
}
}
Is there any relation between legacyDBThread and newDBThread ? legacyDBThread和newDBThread之间有任何关系吗? If I want newDBThread to execute some code and then wait for legacyDBThread to finish and then continue running.
如果我希望newDBThread执行一些代码,然后等待legacyDBThread完成,然后继续运行。 How can this be achieved ?
如何实现呢?
wait()
and notify()
API is helpful here. wait()
和notify()
API很有帮助。 you can share some objects in two class and use wait-notify
on these shared objects to sync two thread. 您可以在两个类中共享一些对象,并在这些共享对象上使用
wait-notify
来同步两个线程。
You can use countdown latch. 您可以使用倒数锁存器。 Create a count down latch with count one, pass it to
legacyDAOObj
. 创建一个计数为1的倒数锁存器,并将其传递给
legacyDAOObj
。 After the logic executed in legacyDAOObj
, count down the latch. 在
legacyDAOObj
执行逻辑之后,递减锁存器。 Till the logic is executed in legacyDAOObj
, newDAOObj
awaits. 直到逻辑在
legacyDAOObj
执行, newDAOObj
等待。
如果只想等待线程结束,请使用Thread#join() ,这似乎是实现所需目标的最简单方法。
CountdownLatch
will be your best bet. CountdownLatch
将是您最好的选择。 Your newDaoObj
will continue in main thread once legacyDaoObj
finishes. 一旦
legacyDaoObj
完成,您的newDaoObj
将继续在主线程中。
public static void main(String[] args) {
CountDownLatch start =new CountDownlatch(1);
LegacyDAO legacyDAOObj= new LegacyDAO();
NewDAO newDAOObj= new NewDAO();
new Thread(new Worker(legacyDAOObj)).start();
try {
start.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
newDAOObj.doSomething();
}
public static class Worker implements Runnable{
LegacyDAO dao;
public Worker(LegacyDAO dao) {
this.dao = dao;
}
@Override
public void run() {
try {
start.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
dao.doSomething();
start.countDown();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.