Java wait和join方法之间的区别
在多线程中,当我们处理线程时,会出现暂停和启动线程的要求,为此线程提供了两种方法,分别用于等待和连接。
以下是wait()和join()之间的重要区别。
wait()vsjoin()的示例
JavaTester.java
public class JavaTester extends Thread { static Object lock = new Object(); static int n; int i; String name; JavaTester(String name, int i) { this.name = name; this.i = i; } @Override public void run() { try { synchronized (lock) { while (i != n) { lock.wait(); } System.out.println(name + " started"); n++; lock.notifyAll(); } synchronized (lock) { while (i != n - 4) { lock.wait(); } System.out.println(name + " finished"); n++; lock.notifyAll(); } } catch (InterruptedException e) { } } public static void main(String[] args) throws Exception { new JavaTester("a", 0).start(); new JavaTester("b", 1).start(); new JavaTester("c", 2).start(); new JavaTester("d", 3).start(); } }
输出结果
a started b started c started d started a finished b finished c finished d finished