我有ExecutorService
并开始2个帖子。
public class Test {
private final ExecutorService threadPool = Executors.newFixedThreadPool(3);
public void start() {
threadPool.submit(new Runnable() {
public void run() {
for (int i = 0; i < 10; i++) {
if (!Thread.interrupted()) {
try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
System.out.println("subject 1 stopped!");
Thread.currentThread().interrupt(); // restore interrupted status
return;
}
System.out.println("Hello!");
}
}
}
});
threadPool.submit(new Runnable() {
public void run() {
for (int i = 0; i < 10; i++) {
if (!Thread.interrupted()) {
try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
System.out.println("subject 2 stopped!");
Thread.currentThread().interrupt(); // restore interrupted status
return;
}
System.out.println("By!");
}
}
}
});
}
public void stop() {
threadPool.shutdownNow();
}
}
在Main class我想停一个Thread
public class Main {
public static void main(String args[]) throws InterruptedException {
System.out.println("Start");
Test test = new Test();
test.start();
Thread.sleep(5000);
test.stop();
}
}
如何停止/暂停某些线程?