zoukankan      html  css  js  c++  java
  • 多线程停止的方法

    线程停止有基本的两种思路:

    执行stop()函数,但是不够安全,这是一个强制结束线程的方式,

    任务结束,自己停止。(常用方法)

    1.标记停止的方法。

    弊端:在多个线程的情况下,当有一个线程处于等待状态时,此时停止线程,则无法停止处于等待中的线程。

    示例:设置标记flag,控制线程结束。

    class StopThread implements Runnable{
    private boolean flag = true;
    public void run (){
    while(flag){
    System.out.println(Thread.currentThread().getName()+"run ");
    }
    }

    public void setFlag(){
    this.flag =false;;

    }
    }

    class ProduceDemo{
    public static void main(String[] arg){

    StopThread stop = new StopThread();
    Thread t1 = new Thread(stop);
    Thread t2 = new Thread(stop);
    t1.start();
    t2.start();
    int i = 0;
    while(true){
    if(i == 50){
    stop.setFlag();
    break;
    }
    System.out.println("main");
    i++;
    }
    }
    }

    下面这种用标记法就不行,就算标记设置为了false,但是出于wait中的线程无法结束任务。

    class StopThread implements Runnable{
    private boolean flag = true;

    public synchronized void run (){
    while(flag){
    try{
    wait();
    }
    catch(Exception e){
    System.out.println("Exception ");
    };
    System.out.println(Thread.currentThread().getName()+"********");
    }

    }
    public void setFlag(){
    this.flag =false;

    }


    }

    class ProduceDemo{
    public static void main(String[] arg){

    StopThread stop = new StopThread();
    Thread t1 = new Thread(stop);
    Thread t2 = new Thread(stop);
    t1.start();
    t2.start();

    int i = 0;
    while(true){
    if(i == 50000){
    stop.setFlag();
    break;
    }

    i++;
    }
    System.out.println("over");
    }
    }

    2.interrupt方法

    线程处于冻结状态无法获取标记,如何结束呢?

    可以使用interrupt()方法将线程从冻结状态强制恢复到运行状态中来,让线程具备CPU的执行资格。

    强制动作会发生interruptException,记得处理。

    class StopThread implements Runnable{
    private boolean flag = true;

    public synchronized void run (){
    while(flag){
    try{
    wait();
    }
    catch(Exception e){
    System.out.println("Exception ");
    flag = false;
    };
    System.out.println(Thread.currentThread().getName()+"********");
    }

    }
    public void setFlag(){
    this.flag =false;

    }


    }

    class ProduceDemo{
    public static void main(String[] arg){

    StopThread stop = new StopThread();
    Thread t1 = new Thread(stop);
    Thread t2 = new Thread(stop);
    t1.start();
    t2.start();

    int i = 0;
    while(true){
    if(i == 50000){
    t1.interrupt();
    t2.interrupt();
    break;
    }

    i++;
    }
    System.out.println("over");
    }
    }

    每一步都是一个深刻的脚印
  • 相关阅读:
    Java运行环境(win10)
    maven封装jar包遇到的问题
    eclipse安装STS遇到的问题
    Redis IO多路复用的理解
    操作系统文章推荐
    jdk1.8新特性
    Maven笔记
    博主推荐
    MySQL文章推荐
    多线程文章推荐
  • 原文地址:https://www.cnblogs.com/chzlh/p/9278611.html
Copyright © 2011-2022 走看看