多线程的停止方法stop已经过时,所以停止线程的方法只有一种,run方法结束。因为多线程

运行的代码通常都是循环结构的,只要控制住循环就可以让run方法结束,也就是线程结束。(使用标记控制循环)

 

PS:

特殊情况:

当线程处于了冻结状态,就不会读取到标记,那么线程就不会结束。

当没有指定的方法让冻结的线程恢复运行时,需要对冻结状态进行清除,

Thread类提供了专门用于清除线程冻结状态的方法——interrupt

停止线程示例:

class stopThreadDemo 
{
    public static void main(String[] args) 
    {
        //创建并开启两个线程
        stopThread st = new stopThread();

        Thread t1 = new Thread(st);
        Thread t2 = new Thread(st);

        t1.start();
        t2.start();
        //创建一个计数器
        int num = 0;
        //主线程中循环输出
        //若当主线程输出了60句则停止输出并改变标记停止开启的两条线程。
        while (true)
        {
            if (num++ == 60)
            {
                st.changeFlag();
                break;
            }
            System.out.println(Thread.currentThread().getName()+"............."+num);
        }
            
    }
}

class stopThread implements Runnable
{
    private boolean flag = true;
    public void run()
    {
        while (flag)
        {
            System.out.println(Thread.currentThread().getName()+"...run...");
        }
    }
//修改标记的方法
    public void changeFlag()
    {
        flag = false;
    }
}
通过标记停止线程

相关文章:

  • 2021-10-13
  • 2021-12-12
  • 2022-01-13
  • 2021-12-15
  • 2021-07-19
  • 2021-12-15
  • 2021-11-02
  • 2017-12-01
猜你喜欢
  • 2022-12-23
  • 2022-03-05
  • 2021-12-15
  • 2022-12-23
  • 2021-12-05
  • 2021-11-02
  • 2022-12-23
相关资源
相似解决方案