如何通过另一个线程停止线程? [英] How to stop a thread by another thread?

查看:282
本文介绍了如何通过另一个线程停止线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Java中遇到了一些线程,我有三个线程 - thread1,thread2和thread3。它们在启动时正在做一些任务,我想通过thread1来阻止这两个线程。我把thread1用于 sleep(500),然后我停止了两个线程,但是两个线程的进程仍在运行。你知道怎么做吗?

I have some struggle with threads in Java, I have three threads - thread1, thread2, and thread3. Those are doing some task when it started, I want to stop these two threads by thread1. I put thread1 for sleep(500), then I stop the both threads, but the process of two threads are still running. Do you have any idea how to do this?

推荐答案

你是怎么试图阻止他们的? 使用Thread.stop ?请注意,此方法已弃用。

How're you attempting to stop them? Thread.stop? Be warned that this method is deprecated.

相反,请考虑使用线程1的某种标志与线程2和3通信它们应该停止。实际上,您可以使用中断

Instead, look into using some sort of flag for thread 1 to communicate to thread 2 and 3 that they should stop. In fact, you could probably use interrupts.

下面, Thread.interrupt 用于实现协调。

final Thread subject1 = new Thread(new Runnable() {

  public void run() {
    while (!Thread.interrupted()) {
      Thread.yield();
    }
    System.out.println("subject 1 stopped!");
  }
});
final Thread subject2 = new Thread(new Runnable() {

  public void run() {
    while (!Thread.interrupted()) {
      Thread.yield();
    }
    System.out.println("subject 2 stopped!");
  }
});
final Thread coordinator = new Thread(new Runnable() {

  public void run() {
    try {
      Thread.sleep(500);
    } catch (InterruptedException ex) { }
    System.out.println("coordinator stopping!");
    subject1.interrupt();
    subject2.interrupt();
  }
});
subject1.start();
subject2.start();
coordinator.start();






或者,您也可以使用 volatile boolean (或 AtomicBoolean )作为沟通的手段。
原子访问 volatile java.util.concurrent.atomic。* 允许您确保主题线程看到标志的突变。


Alternatively, you could also use a volatile boolean (or AtomicBoolean) as means of communicating. Atomic access provided by volatile and java.util.concurrent.atomic.* allow you to ensure mutation of the flag is seen by the subject threads.

final AtomicBoolean running = new AtomicBoolean(true);

final ExecutorService subjects = Executors.newFixedThreadPool(2);
subjects.submit(new Runnable() {

  public void run() {
    while (running.get()) {
      Thread.yield();
    }
    System.out.println("subject 1 stopped!");
  }
});
subjects.submit(new Runnable() {

  public void run() {
    while (running.get()) {
      Thread.yield();
    }
    System.out.println("subject 2 stopped!");
  }
});
final ScheduledExecutorService coordinator = Executors.newSingleThreadScheduledExecutor();
coordinator.schedule(new Runnable() {

  public void run() {
    System.out.println("coordinator stopping!");
    running.set(false);
    subjects.shutdown();
    coordinator.shutdown();
  }
}, 500, TimeUnit.MILLISECONDS);

同样,你可以选择,而不是使用 AtomicBoolean ,使用如下字段:

Similarly, you could opt to, rather than use AtomicBoolean, use a field such as:

static volatile boolean running = true;






更好的是,如果你利用 ExecutorService ,你也可以编写如下代码:


Better yet, if you take advantage of ExecutorServices, you can also program similar code as follows:

final ExecutorService subjects = Executors.newFixedThreadPool(2);
subjects.submit(new Runnable() {

  public void run() {
    while (!Thread.interrupted()) {
      Thread.yield();
    }
    System.out.println("subject 1 stopped!");
  }
});
subjects.submit(new Runnable() {

  public void run() {
    while (!Thread.interrupted()) {
      Thread.yield();
    }
    System.out.println("subject 2 stopped!");
  }
});
final ScheduledExecutorService coordinator = Executors.newSingleThreadScheduledExecutor();
coordinator.schedule(new Runnable() {

  public void run() {
    System.out.println("coordinator stopping!");
    subjects.shutdownNow();
    coordinator.shutdown();
  }
}, 500, TimeUnit.MILLISECONDS);

这利用了ThreadPoolExecutor.shutdownNow 中断其工作线程以尝试发出关闭信号。

This takes advantage of the fact that ThreadPoolExecutor.shutdownNow interrupts its worker threads in an attempt to signal shutdown.

运行任何一个例子,输出应该是这样的结果:

Running any example, the output should be something to the effect of:

C:\dev\scrap>javac CoordinationTest.java

C:\dev\scrap>java CoordinationTest
coordinator stopping!
subject 1 stopped!
subject 2 stopped!

注意最后两行可以按任意顺序排列。

Note the last two lines can come in either order.

这篇关于如何通过另一个线程停止线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆