015.4守护线程和join

内容:守护线程、join方法
#####################守护线程
通过开启线程之前调用setDaemon()方法,变成后台线程,前台线程运行完,后台线程自动会结束
#########例子

class Demo implements Runnable
{
    private boolean flag = true;
    public synchronized void run()
    {
        while(flag)
        {
            try
            {
                wait();//t1  t2
            }
            catch (InterruptedException e)
            {
                System.out.println(Thread.currentThread().toString()+"....."+e.toString());
                changeFlag();
            }

            System.out.println(Thread.currentThread().getName()+"----->");
        }
    }
    //对标记的修改方法。
    public void changeFlag()
    {
        flag = false;
    }
}


class StopThreadDemo 
{
    public static void main(String[] args) 
    {
        Demo d = new Demo();

        Thread t1 = new Thread(d,"旺财");
        Thread t2 = new Thread(d,"小强");
        t1.start();
        //将t2标记为后台线程,守护线程。
//        t2.setDaemon(true);
        t2.start();

        int x = 0;
        while(true)
        {
            if(++x == 50)//条件满足。
            {
//                d.changeFlag();//改变线程任务代码的标记,让其他线程也结束。
                //对t1线程对象进行中断状态的清除,强制让其恢复到运行状态。
                t1.interrupt();
                //对t2线程对象进行中断状态的清除,强制让其恢复到运行状态。
                t2.interrupt();

                break;//跳出循环,主线程可以结束。
            }
            System.out.println("main-------->"+x);
        }

        System.out.println("over");
    }
}
View Code

#################join方法
哪个线程调用了,就需要等待该线程结束,整个进程才会结束

 1 class Demo implements Runnable
 2 {
 3 
 4     public void run()
 5     {
 6         for(int x=1; x<=40; x++)
 7         {
 8             System.out.println(Thread.currentThread().getName()+"------>"+x);
 9             Thread.yield();//线程临时暂停。将执行权释放,让其他线程有机会获取执行权。
10         }
11     }
12 
13 }
14 
15 class JoinThreadDemo 
16 {
17     public static void main(String[] args) 
18     {
19         Demo d = new Demo();
20         Thread t1 = new Thread(d);
21         Thread t2 = new Thread(d);
22 
23         t1.start();
24         t2.start();
25         //主线程执行到这里,知道t1要加入执行,主线程释放了执行权,
26         //执行资格并处于冻结状态,什么时候恢复呢?等t1线程执行完。
27 //        try{t1.join();}catch(InterruptedException e){}//用于临时加入一个运算的线程。让该线程运算完,程序才会继续执行。
28 
29         for(int x=1; x<=50; x++)
30         {
31             System.out.println("main---------->"+x);
32         }
33         System.out.println("over");
34     }
35 }
View Code

 

设置优先级

 

posted @ 2018-03-27 09:01  Alos403  阅读(264)  评论(0编辑  收藏  举报