0
private void stopThread() {
thread1.canRun(false);
}
private void createThread() {
thread1.stopThread();
thread1.canRun(true);
thread1 = new Thread(thread1);
t.start();
}
버튼은 하나뿐입니다. 버튼을 클릭하면 다시 버튼을 클릭하면 새 스레드가 멈추고 새로 만들어야합니다. 숫자가 인 스레드가 실행됩니다.동일한 변수를 사용하는 두 개의 스레드
thread1.stopThread(); // <-- sets canRun to false
thread1.canRun(true); // <-- sets canRun to back to true
또한 canRun
를 초기화 할 수 있습니다 : 내가 두 번째 만들 그것은 마지막 하나 나던 정지를 보인다 둘 다 문제는이 라인에있을 수 있습니다
@Override
public void run() {
try {
for (int i = 0; i <= TimeOut && canRun; i++) {
System.out.println(i);
Thread.sleep(1000);
}
}
private volatile boolean canRun;
마지막 스레드가 실행되지 않도록 멈추십시오. – AlanRubinoff
코드 발췌에서'canRun (true)'가'thread1.stopThread()'를 다시 설정하는 것처럼 보입니다. 따라서이 줄을 제거하면됩니다. –
canRun을 true로 초기화 할 수도 있습니다. 내 업데이트를 참조하십시오. –