美文网首页
[Java][Thread需要了解的那些事之主要方法的使用]

[Java][Thread需要了解的那些事之主要方法的使用]

作者: lgy_gg | 来源:发表于2017-09-27 18:09 被阅读0次

    1.sleep()

    作用是让当前线程按照给定的时间段休眠,但是并不能保证当前线程完全精确的按照给定的时间段休眠。也就是说如果当前线程调用sleep(1000),也就是设定了休眠时间是1000毫秒,那么当前线程有可能是休眠了999毫秒或者1001毫秒。它使当前线程从running状态进入到block状态,等到休眠结束后再进入到runable状态。
    在多线程但当前线程和其他线程没有锁着同一个对象的时候,其他线程是能得到机会执行的。

        private void newThread(final String name,final boolean isSleep)
        {
            new Thread(new Runnable() {
                
                @Override
                public void run() {
                    
                    for (int i = 0; i < 5; i++) {
                        Log.i("lgy", name+":"+i);
                        try {
                            if (isSleep) {
                                Thread.sleep(1000);
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        
                    }
                }
            },name).start();
        }
    调用:
            newThread("thread 1",true);
            newThread("thread 2",false);
            newThread("thread 3",false);
    输出:
    09-27 10:38:36.516: I/lgy(13561): thread 1:0
    09-27 10:38:36.516: I/lgy(13561): thread 2:0
    09-27 10:38:36.517: I/lgy(13561): thread 2:1
    09-27 10:38:36.517: I/lgy(13561): thread 2:2
    09-27 10:38:36.517: I/lgy(13561): thread 2:3
    09-27 10:38:36.517: I/lgy(13561): thread 3:0
    09-27 10:38:36.517: I/lgy(13561): thread 3:1
    09-27 10:38:36.517: I/lgy(13561): thread 3:2
    09-27 10:38:36.517: I/lgy(13561): thread 3:3
    09-27 10:38:36.517: I/lgy(13561): thread 3:4
    09-27 10:38:36.519: I/lgy(13561): thread 2:4
    09-27 10:38:37.516: I/lgy(13561): thread 1:1
    09-27 10:38:38.516: I/lgy(13561): thread 1:2
    09-27 10:38:39.517: I/lgy(13561): thread 1:3
    09-27 10:38:40.517: I/lgy(13561): thread 1:4
    

    在多线程但当前线程和其他线程锁着同一个对象的时候,其他线程是会进入blocked状态,直到当前线程释放锁后,他们才有机会被执行。当然,进入blocked状态的线程会回到runable状态,然后才会被cpu调度执行。可以知道sleep()方法是不会释放锁的。

        private void newThread2(final String name, final boolean isSleep) {
            new Thread(new Runnable() {
    
                @Override
                public void run() {
                    synchronized (object) {
                        for (int i = 0; i < 5; i++) {
    
                            Log.i("lgy", name + ":" + i);
                            try {
                                if (isSleep) {
                                    Thread.sleep(1000);
                                }
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }, name).start();
        }
    调用:
            newThread2("thread 1", true);
            newThread2("thread 2", false);
            newThread2("thread 3", false);
    输出:
    09-27 11:01:06.369: I/lgy(17400): thread 1:0
    09-27 11:01:07.369: I/lgy(17400): thread 1:1
    09-27 11:01:08.370: I/lgy(17400): thread 1:2
    09-27 11:01:09.370: I/lgy(17400): thread 1:3
    09-27 11:01:10.370: I/lgy(17400): thread 1:4
    09-27 11:01:11.371: I/lgy(17400): thread 3:0
    09-27 11:01:11.371: I/lgy(17400): thread 3:1
    09-27 11:01:11.371: I/lgy(17400): thread 3:2
    09-27 11:01:11.371: I/lgy(17400): thread 3:3
    09-27 11:01:11.371: I/lgy(17400): thread 3:4
    09-27 11:01:11.371: I/lgy(17400): thread 2:0
    09-27 11:01:11.371: I/lgy(17400): thread 2:1
    09-27 11:01:11.371: I/lgy(17400): thread 2:2
    09-27 11:01:11.371: I/lgy(17400): thread 2:3
    09-27 11:01:11.371: I/lgy(17400): thread 2:4
    

    sleep(long time)
    当前线程休眠time毫秒,不能小于0,time<0会抛出异常。
    sleep(long millis, int nanos)
    使当前线程暂停millis毫秒nanos纳秒。需要注意的是,参数nanos的取值范围为[0, 999999]。

    2.yield()

    作用是当前线程会让出执行时间,让其他处于runable状态的线程有机会运行。但是,我们需要明白当前线程调用yield()方法会让当前的线程进入到runable状态。所以,这里可能会存在这么一种情况,就是当当前线程调用yield()后进入到runable状态,当前线程和其他线程都同处于runable状态,当前线程可能会在让出执行时间后,又会再次被调用执行。
    在多线程且当前线程和其他线程都没有加锁的情况下,也设置了优先级,在android里多次测试得到的输出结果,调用了yield()方法的线程并没有让出执行机会给其他线程,这里我无法断定在android项目下调用yield()方法的线程也不会让出执行机会,只是说我测了多次都没有发现它有让出执行机会的行为,具体什么缘由不太清楚。但是如果在Java project下,可以明显的看出当前线程是有让出执行机会的行为的。而且线程优先级比当前线程高的线程被执行的机会更大。但是线程的优先级仍然无法保证它会先被执行。只不过,优先级高的线程获取CPU资源的概率较大,优先级低的并非没机会执行。

        private void newThread3(final String name,final boolean isYield,int PRIORITY) {
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    if (isYield) {
                        Thread.yield();
                    }
                    for (int i = 0; i < 5; i++) {
                        Log.i("lgy", name + ":" + i);
                    }
                }
            }, name);
            thread.setPriority(PRIORITY);
            thread.start();
        }
    调用
            newThread3("thread 1", true,5);
            newThread3("thread 2", false,Thread.MAX_PRIORITY);
            newThread3("thread 3", false,Thread.MIN_PRIORITY);
            newThread3("thread 4", false,Thread.MIN_PRIORITY);
            newThread3("thread 5", false,5);
    

    输出(android project的输出结果,整篇文章的输出结果都是android project的输出结果)

    image.png

    在多线程且当前线程和其他线程加锁的情况下,也设置了优先级。在android里多次测试得到的输出结果,调用了yield()方法的线程并没有让出执行机会给其他线程。不管是在android project里执行还是在java project中,都是某个线程执行完后,其他线程才有能执行,所以yield()方法是不会释放锁的。

        private void newThread4(final String name,final boolean isYield,int PRIORITY) {
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    synchronized (object) {
                        if (isYield) {
                            Thread.yield();
                        }
                        for (int i = 0; i < 5; i++) {
                            Log.i("lgy", name + ":" + i);
                        }
                    }
    
                }
            }, name);
            thread.setPriority(PRIORITY);
            thread.start();
        }
    调用
            newThread4("thread 1", false,Thread.MIN_PRIORITY);
            newThread4("thread 2", true,5);
            newThread4("thread 3", false,Thread.MAX_PRIORITY);
            newThread4("thread 4", false,5);
    
    

    输出

    image.png

    3.join()

    作用是让“父线程”等待“子线程”,直到子线程结束或者超时过期,“父线程”才能继续运行。这个方法会阻塞父线程,让父线程进入到block状态,直到子线程结束或者超时过期,父线程才能进入runable状态。
    join()
    如果调用这个方法,“父线程”必须等待“子线程” 结束,才能执行父线程。
    join(long millis)
    这里的millis是设置超时的,单位是毫秒,也就是说,如果在millis毫秒内,即使子线程还没有执行,父线程也可以获得执行。例如thread2.join(5000);则让父线程等待5000毫秒,如果超过这个时间,父线程则停止等待,变为可运行状态。
    join(long millis, int nanos)
    这个方法和上面的差不多,只不过是超时限制单位精确到了纳秒。和sleep()一样,如果这里的millis或nanos小于0,则会抛出异常。

        private void newThread5(final String name) {
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
    
                        Thread thread2 = new Thread(new Runnable() {
                            
                            @Override
                            public void run() {
    //这里是为了测试超时后,父线程是否会执行,测试结果是如果子线程join超时了,父线程是会执行的
                                try {
                                    Thread.sleep(10*1000);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                                for (int i = 0; i < 5; i++) {
                                    Log.i("lgy",  "innerThread:" + i);
                                }
                                
                            }
                        });
                        thread2.start();
                        try {
                            thread2.join(5000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        
                        for (int i = 0; i < 5; i++) {
                            Log.i("lgy", name + ":" + i);
                        }
                }
            }, name);
            thread.start();
        }
    调用
            newThread5("thread 1");
    

    输出

    image.png

    4.interrupt()

    interrupted方法本质只是设置当前线程的中断标志,将中断标志设置为true,并根据线程状态决定是否抛出异常。这个方法并不会中断一个正在运行的线程。

        private void newThread6(final String name) {
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                        
                        for (int i = 0; i < 5; i++) {
                            if (i==3) {
                                try {
                                    Thread.sleep(3000);
                                    //下面这样设置中断是不会抛出异常的
    //                              boolean b = Thread.interrupted();
    //                              Log.i("lgy", name + " is interrupted " + b);
                                } catch (InterruptedException e) {
                                    Log.i("lgy", name + " throw InterruptedException ");
                                    return;
                                }
                            }
                            Log.i("lgy", name + ":" + i);
                        }
                }
            }, name);
            thread.start();
            Log.i("lgy", name + " is interrupted " + thread.isInterrupted());
            thread.interrupt();
            Log.i("lgy", name + " is interrupted " + thread.isInterrupted());
        }
    调用
    newThread6("thread 1");
    

    输出

    image.png

    5.wait和notify

    wait和notify都不是Thread里的方法,而是Object的方法,它们是用于同步块中。wait()的作用是让当前线程进入等待状态,同时,wait()也会让当前线程释放它所持有的锁。直到其他线程调用此对象的 notify() 方法或 notifyAll()方法或者超过指定的时间量”,当前线程被唤醒,进入runable状态。notify只会通知一个在等待的对象,而notifyAll会通知所有在等待的对象,并且所有对象都会继续运行。Wait()方法调用是会释放锁的。

        private void newThread7(final String name,final boolean isWait,final boolean isNotify) {
            new Thread(new Runnable() {
    
                @Override
                public void run() {
                    synchronized (object) {
                        if (isNotify) {
                            object.notifyAll();
                        }
                        for (int i = 0; i < 5; i++) {
                            if (i==3&&isWait) {
                                try {
                                    object.wait();
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                            Log.i("lgy", name + ":" + i);
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }, name).start();
        }
    调用
            newThread7("thread 1",true,false);
            newThread7("thread 2",true,false);
            newThread7("thread 3",false,true);
            newThread7("thread 4",false,false);
    

    输出

    image.png

    6.源码地址

    Android Project例子
    Java Project例子

    7.参考文章

    http://www.cnblogs.com/skywang12345/p/3479275.html
    http://blog.csdn.net/xiaogutou1/article/details/47443795
    http://blog.csdn.net/bigtree_3721/article/details/51247245
    http://www.cnblogs.com/wxd0108/p/5479442.html
    http://www.importnew.com/21501.html

    相关文章

      网友评论

          本文标题:[Java][Thread需要了解的那些事之主要方法的使用]

          本文链接:https://www.haomeiwen.com/subject/njauextx.html