停止できるスレッド——return法(菜鳥遊びスレッド)
10058 ワード
停止できるスレッド_returnを使用してスレッドを停止する
実装コードは次のとおりです.
実装コードは次のとおりです.
package com.thread8;
public class MyThread extends Thread {
@Override
public void run() {
super.run();
while (true) {
if (this.isInterrupted()) {
System.out.println(" !!");
return;
}
System.out.println("timer = " + System.currentTimeMillis());
}
}
}
package com.fiberhome.thread8;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
public class Run {
public static void main(String[] args) {
File f = new File("out.txt");
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(f);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
PrintStream printStream = new PrintStream(fileOutputStream);
System.setOut(printStream);
try {
MyThread myThread = new MyThread();
myThread.start();
Thread.sleep(2000);
myThread.interrupt();
} catch (InterruptedException e) {
System.out.println("main catch");
e.printStackTrace();
}
System.out.println("end!!");
}
}
timer = 1541148698257
timer = 1541148698257
timer = 1541148698257
timer = 1541148698257
timer = 1541148698257
timer = 1541148698257
timer = 1541148698257
timer = 1541148698257
timer = 1541148698258
timer = 1541148698258
timer = 1541148698258
timer = 1541148698258
timer = 1541148698258
timer = 1541148698258
end!!
!!
, interrupt() return
“ ” , catch , 、 , return; 。