我的任务是按以下顺序创建线程:如果A开始->启动B和C,如果B开始->启动D。并以相反的顺序销毁它们如果D然后B。如果B和C然后A。它。我设法做到了,但我想还有更好的方法。你有什么建议吗?
在您发表评论后,我更改了代码,这非常简单。但是现在看起来“愚蠢”。我想更改if语句和实现的硬性,有什么建议吗?寻求建议,我正在与您一起学习。
这是我的新代码:
import java.util.*; class RobotController implements Runnable{ String name; public void run() { Thread t = Thread.currentThread(); System.out.println(t.getName() + " status = " + t.isAlive()); System.out.println(t.getName() + " status = " + t.getState()); } public static void main(String args[]) throws InterruptedException{ Thread thread_A = new Thread(new RobotController(), "Thread A"); Thread thread_B = new Thread(new RobotController(), "Thread B"); Thread thread_C = new Thread(new RobotController(), "Thread C"); Thread thread_D = new Thread(new RobotController(), "Thread D"); thread_A.start(); thread_A.join(); System.out.println(thread_A.getState()); thread_B.start(); thread_B.join(); System.out.println(thread_B.getState()); thread_C.start(); thread_C.join(); System.out.println(thread_C.getState()); thread_D.start(); System.out.println(thread_D.getState()); } }
您的代码中存在一些缺陷,这些缺陷有时会使它无法相应地工作:
thread_A.start()
thread_A.isAlive()
thread_B
thread_C
thread_A
thread_B.isAlive()
if
thread_D
现在需要考虑的一点是: 在join()调用其方法之后,无需检查线程是否处于活动状态。这是不必要的运行时开销。
join()
编辑 好,这是代码的修改版本。.我希望它可以让您了解线程的动态:
class RobotController implements Runnable { private final Object lock = new Object(); private void notifyThread() { synchronized(lock) { lock.notify(); } } public void run() { synchronized(lock) { try { System.out.println(Thread.currentThread().getName() + " started"); lock.wait(); System.out.println(Thread.currentThread().getName()+ " stopped"); } catch (InterruptedException ex) { ex.printStackTrace(); } } } public static void main(String args[]) throws InterruptedException { RobotController rca = new RobotController(); RobotController rcb = new RobotController(); RobotController rcc = new RobotController(); RobotController rcd = new RobotController(); Thread thread_A = new Thread(rca,"Thread A"); Thread thread_B = new Thread(rcb,"Thread B"); Thread thread_C = new Thread(rcc,"Thread C"); Thread thread_D = new Thread(rcd,"Thread D"); thread_A.start(); while (thread_A.getState() != Thread.State.WAITING) { Thread.sleep(100); } thread_B.start(); thread_C.start(); while (thread_B.getState() != Thread.State.WAITING && thread_C.getState() != Thread.State.WAITING) { Thread.sleep(100); } thread_D.start(); while (thread_D.getState() != Thread.State.WAITING) { Thread.sleep(100); } rcd.notifyThread(); thread_D.join(); rcc.notifyThread(); thread_C.join(); rcb.notifyThread(); thread_B.join(); rca.notifyThread(); } }
这是输出:
Thread A started Thread B started Thread C started Thread D started Thread D stopped Thread C stopped Thread B stopped Thread A stopped