欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

强制让等待的线程获得执行资格,强制等待线程资格,package cn.i

来源: javaer 分享于  点击 15951 次 点评:133

强制让等待的线程获得执行资格,强制等待线程资格,package cn.i


package cn.itcast.gz;/** * 控制循环通常就用定义标记来完成。        但是如果线程处于了冻结状态,无法读取标记。如何结束呢?       可以使用interrupt()方法将线程从冻结状态强制恢复到运行状态中来,让线程具备cpu的执行资格。        当时强制动作会发生了InterruptedException,记得要处理 */public 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.setDaemon(true);        t2.start();        int num = 1;        for(;;)        {            if(++num==50)            {                t1.interrupt();                break;            }            System.out.println("main....."+num);        }        System.out.println("over");    }}class StopThread implements Runnable {    private boolean flag = true;    @Override    public synchronized void run() {        while(flag)        {            try {                wait();            } catch (Exception e) {                System.out.println(Thread.currentThread().getName()+"........"+e);                flag= false;            }            System.out.println(Thread.currentThread().getName()+"++++++++");        }    }    public void setFlag()    {        flag = false;    }}//该片段来自于http://byrx.net
相关栏目:

用户点评