码迷,mamicode.com
首页 > 编程语言 > 详细

多线程(停止线程)

时间:2015-10-25 15:02:30      阅读:220      评论:0      收藏:0      [点我收藏+]

标签:

多线程的停止方法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;
    }
}
通过标记停止线程

特殊情况停止线程示例:

技术分享
class stopThread implements Runnable
{
    private boolean flag = true;
    //线程一运行因标记为真,会进入冻结状态,放弃执行资格。
    public synchronized void run()
    {
        int num = 0;
        while (flag)
        {
            try
            {
                this.wait();
            }
            catch (InterruptedException e)
            {
                //若线程被强制唤醒则会抛出一个InterruptedException(中断异常)
                System.out.println(Thread.currentThread().getName()+"..Exception..");
                //如果发生了InterruptedException(中断异常)则说明有人在强制唤醒线程,而唤醒的目的是为了让线程结束
                this.changeFlag();
            }
            System.out.println(Thread.currentThread().getName()+"...运行了..."+num++);
        }
    }
//修改标记的方法
    public void changeFlag()
    {
        flag = false;
    }
}

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句则停止输出,并通过interrupt方法将陷入休眠状态的线程强制唤醒。
        while (true)
        {
            if (num++ == 60)
            {
                t1.interrupt();
                t2.interrupt();
                break;
            }
            System.out.println(Thread.currentThread().getName()+"............."+num);
        }
            
    }
}
当线程冻结时结束线程的方法

 

多线程(停止线程)

标签:

原文地址:http://www.cnblogs.com/gzc911/p/4908681.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!