내 자바 프로그램에 두 개의 스레드가 있는데, 하나는 주 스레드이고 다른 스레드는 주 스레드에서 생성 된 스레드 A입니다. 이제는 주 스레드가 스레드 A를 시작하고 스레드 A가 실행 방법에서 코드의 일부를 실행하고 스레드 A가 자체를 일시 중단해야 할 때까지 기다려야합니다. 메인 쓰레드는 실행을 시작하고, 몇 줄의 코드를 실행 한 다음 다시 쓰레드 A가 멈춘 곳에서 시작해야하고, 그 반대도 마찬가지입니다. 이것은 n 번 반복해야합니다. 내가는 belows로 노력하고 있어요 :자바에서 두 스레드 동기화
public class ThreadA implements Runnable {
boolean suspended = false;
boolean stopped = false;
synchronized void stop() {
stopped = true;
suspended = false;
notify();
}
synchronized void suspend() {
suspended = true;
}
synchronized void resume() {
suspended = false;
notify();
}
void job() throws InterruptedException {
for (int i = 0; i < 5; i++)
synchronized (this) {
System.out.println("performing job.");
suspend();
while (suspended) {
notify();
suspended = false;
}
}
}
@Override
public void run() {
try {
job();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
MainThread :
public class MainThread {
public static void main(String[] args) throws InterruptedException {
ThreadA a1=new ThreadA();
Thread t1=new Thread(a1);
synchronized (t1) {
t1.start();
for (int i = 0; i < 5; i++) {
t1.wait();
System.out.println("perform some action");
a1.resume();
}
}
}
}
예상 출력 :
performing job.
perform some action
performing job.
perform some action
performing job.
perform some action
performing job.
perform some action
performing job.
perform some action
실제 출력 :
이 클래스 스레드
작업 방법에서 notify() 신호를 발행 한 경우에도 전체 for 루프가 스레드 A에서 실행되는 이유를 알 수 없습니다.
더 단순화? 당신은 단지 하나의 쓰레드로 똑같이 할 수있다. – JohnnyAW
Sidenote : 서로 다른 객체에있는 두 개의 쓰레드를 동기화 시키므로,'synchronized' 문은 꽤 쓸모가 없다. – Thomas
완전 무작위로 기대하십니까? 또는 작업 - 작업 - 작업 - 단계에서? –