Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/cocoa/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
java线程通知_Java_Multithreading - Fatal编程技术网

java线程通知

java线程通知,java,multithreading,Java,Multithreading,我有两个班,fe一班和fe二班 假设我在第1课中这样做: Class2 class2 = new Class2(); Thread thread = new Thread(class2); thread.start(); ... thread.stop(); 现在我想在线程停止时签入Class2的run方法,我该怎么做? 因此,当class1停止线程时,我想向class2发出一些警报,提醒它已停止,然后执行一些操作 不要使用stop(),使用interrupt() 如果您遵守第1点,在Clas

我有两个班,fe一班和fe二班

假设我在第1课中这样做:

Class2 class2 = new Class2();
Thread thread = new Thread(class2);
thread.start();
...
thread.stop();
现在我想在线程停止时签入Class2的run方法,我该怎么做? 因此,当class1停止线程时,我想向class2发出一些警报,提醒它已停止,然后执行一些操作

  • 不要使用
    stop()
    ,使用
    interrupt()

  • 如果您遵守第1点,在
    Class2
    中,您可以使用:


  • 一旦线程“停止”,这意味着
    run
    方法是
    Class2
    已退出。因此,在线程停止后执行
    run
    方法中没有一种方法可以让代码运行

    您可以监听中断并处理该中断,但该处理将在线程仍在运行时完成


    您还可以在
    Class2
    中使用不同的方法,一旦线程停止,您可以从
    Class1
    调用该方法。

    首先,不要使用thread.stop(),因为它已被弃用。因此,依靠这些方法是不可取的。 第二:有多种解决方法(基本上是尝试关机或通信)

  • 使用通知消息的标志。但要确保整个调用是线程安全的。并及时保持检查标志是否已设置。如果设置了,则执行所需的操作
  • 中断是通知其他线程的完美方式。维护和中断策略(Maintenance and interruption policy)表示:当在线程A上抛出中断时,A的中断策略是关闭。每当它收到一个中断。在一个可运行的模式下,使其能够及时检查中断,如果设置了中断,则关闭服务。 通过检查状态
    Thread.currentThread().isInterrupted()
    通常,中断主要用于通知其他人它正在请求关机。(Brian Goetz的“实践中的并发性”有一个很好的章节)

  • 你的类2应该得到一个InterruptedException,就这样。顺便提一下 ()


    出于兴趣,你想要实现什么

    你读过
    线程停止的API文档了吗?在停止线程后,只需调用class2的一个方法:thread.stop();类别2.剂量测定法()@Thomas Uhrig:这仍然是最好的答案,因为它做了所需的事情,并指出了现有代码中的一个严重问题。不应该使用Thread.stop()的主要原因并不是因为它已被弃用,但它被弃用的原因是:它可能使应用程序处于不一致的状态,因为它无法以尊重代码中一致性保证的方式实现。这是一个很好的参考,说明为什么它被弃用。
    
    public void run() {
      if(Thread.currentThread().isInterrupted())
        //somebody interrupted me, ouch!
    }