join
과 wait
은 매우 다른 일을하며 실제로 관련이 없으며, 제공 한 예가 실제로 매우 이상하다는 것을 염두에두면 선택 사항 중 하나가 잠재적으로 사용자가 찾고있는 것일 수 있습니다. .
join
이 더 쉬운 선택 일 수 있습니다. join
을 호출하는 스레드는 다른 스레드가 실행을 마칠 때까지 대기합니다. 따라서이 경우 각 스레드는 스레드에 대한 참조를 보유해야하며 "I 'm finished"인쇄 전에 join
을 호출합니다.
class JoiningThread extends Thread {
// NOTE: UNTESTED!
private String name;
private Thread nextThread;
public JoiningThread(String name) {
this(name, null);
}
public JoiningThread(String name, Thread other) {
this.name = name;
this.nextThread = other;
}
public String getName() {
return name;
}
@Override
public void run() {
System.out.println("Hello I'm thread ".concat(getName()));
if (nextThread != null) {
while(nextThread.isAlive()) {
try {
nextThread.join();
} catch (InterruptedException e) {
// ignore this
}
}
}
System.out.println("I'm finished ".concat(getName()));
}
}
을 그리고 주요 방법이 될 수있다 : 그래서 클래스는 다음과 같을 수
wait
이 무엇
public static void main(String[] args) {
Thread d = WaitingThread("d");
Thread c = WaitingThread("c", d);
Thread b = WaitingThread("b", c);
Thread a = WaitingThread("a", b);
a.start();
b.start();
c.start();
d.start();
try {
a.join();
} catch (InterruptedException e) {}
}
는 notify
또는 notifyAll
가 호출 될 때까지 스레드의 실행을 중지합니다. 따라서 wait
으로이 아이디어를 구현하려면 에 대한 참조를 보유하기 위해 각 스레드가 앞에 있어야합니다. 이 전략은 run
메서드를 wait
으로 호출 한 다음 실행이 끝난 이전 스레드 notify
을 호출하는 것입니다. 그래서 클래스는 다음과 같이 보일 수 있습니다 :
class WaitingThread extends Thread {
// NOTE: UNTESTED!
private Thread previousThread;
private String name;
public WaitingThread(String name) {
this(name, null);
}
public WaitingThread(String name, Thread other) {
this.name = name;
this.previousThread = other;
}
public String getName() {
return name;
}
@Override
public void run() {
System.out.println("Hello I'm thread ".concat(getName()));
// Do other things if required
// Wait to be woken up
while(true) {
synchronized(this) {
try {
wait();
break;
} catch (InterruptedException e) {
// ignore this
}
}
}
System.out.println("I'm finished ".concat(getName()));
// Wake up the previous thread
if (previousThread != null) {
synchronized(previousThread) {
previousThread.notify();
}
}
}
}
할 수있는 메인 스레드에서 모든 것을 최대를 설정 main
방법 :
public static void main(String[] args) {
Thread a = WaitingThread("a");
Thread b = WaitingThread("b", a);
Thread c = WaitingThread("c", b);
Thread d = WaitingThread("d", c);
a.start();
b.start();
c.start();
d.start();
while(true) {
// wake up d once it goes to sleep
if (d.isAlive()) {
d.notify();
}
}
}
Th 두 가지가 실제로 관련이 없습니다. –
스레드의 실행을 일시 중지하려고합니다. 스레드에 대한 Oracle Java 자습서를 참조하십시오. http://docs.oracle.com/javase/tutorial/essential/concurrency/sleep.html – AurA
@BrianRoach가 나에게 설명을 해줄 수 있습니까? 그? 이 경우에는 무엇을 사용해야합니까? – njamanjam