Java停止线程从类运行的所有线程
我需要做的是能够停止从一个实现runnable的线程类运行的所有线程。这就是我的意思:这是我的“线程”课程的开始: 这就是我创建多线程的方式:Java停止线程从类运行的所有线程,java,Java,我需要做的是能够停止从一个实现runnable的线程类运行的所有线程。这就是我的意思:这是我的“线程”课程的开始: 这就是我创建多线程的方式: for (int n = 1; n <= m; n++) { new HTTP(n + 1, str, j, k).start(); } for(int n=1;n首先存储所有线程: ArrayList<Thread> threads = new ArrayList<Thread>(); for (i
for (int n = 1; n <= m; n++) {
new HTTP(n + 1, str, j, k).start();
}
for(int n=1;n首先存储所有线程:
ArrayList<Thread> threads = new ArrayList<Thread>();
for (int n = 1; n <= m; n++) {
Thread t = new HTTP(n + 1, str, j, k);
threads.add(t);
t.start();
}
请确保在HTTP线程中选中isIntrupted()
。因此,您可以执行以下操作:
public class InterruptTest {
static class TThread extends Thread {
public void run() {
while(!isInterrupted()) {
System.out.println("Do Work!!!");
try {
sleep(1000);
} catch (InterruptedException e) {
return;
}
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread t = new TThread();
t.start();
Thread.sleep(4000);
System.out.println("Sending interrupt!!");
t.interrupt();
Thread.sleep(4000);
}
}
停止Java中的线程是一个通过中断实现的协作过程。您可以存储线程并逐个中断它们:
List<Thread> threads = new ArrayList<> ();
for (int n = 1; n <= m; n++) {
Thread t = new HTTP(n + 1, str, j, k);
threads.add(t);
t.start();
}
//later on
for (Thread t : threads) {
t.interrupt();
}
List threads=newarraylist();
对于(int n=1;n首先,启动1000个线程实际上是毫无意义的,因为很少有线程被安排实际并发运行
其次,你不能“停止”线程,你所能做的就是通过协作代码让它们很好地停止
最简单的方法是关闭JVM。我们只希望线程上没有阻塞IO。我尝试了这个方法,但不起作用。它将其设置为在for循环后打印“Threads Stopped”。它打印线程停止,但这些线程上的函数仍在运行。我还尝试了thread.stop()@user1947236在实际的线程实现中,您需要继续检查“Thread.interrupted()”。检查我上面的示例。可能重复的情况很糟糕,不要这样做。最好的方法是让线程池轮询HTTP对象(或使用select和非阻塞io),每个HTTP方法的更新方法将快速更新连接状态并返回。更好的方法是使用HTTP服务器的现成实现。
public class InterruptTest {
static class TThread extends Thread {
public void run() {
while(!isInterrupted()) {
System.out.println("Do Work!!!");
try {
sleep(1000);
} catch (InterruptedException e) {
return;
}
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread t = new TThread();
t.start();
Thread.sleep(4000);
System.out.println("Sending interrupt!!");
t.interrupt();
Thread.sleep(4000);
}
}
List<Thread> threads = new ArrayList<> ();
for (int n = 1; n <= m; n++) {
Thread t = new HTTP(n + 1, str, j, k);
threads.add(t);
t.start();
}
//later on
for (Thread t : threads) {
t.interrupt();
}