初见Java多线程(三、线程的阻塞状态)

来源:互联网 发布:苹果指纹解锁软件 编辑:程序博客网 时间:2024/05/04 00:38

1. 阻止线程执行

对于线程的阻塞状态,考虑一下三个方面,不考虑IO阻塞的情况:
睡眠;
等待;
因为需要一个对象的锁定而被阻塞。

2. 睡眠

Thread.sleep(long millis);Thread.sleep(long millis, int nanos);

该静态方法强制当前正在执行的线程休眠(暂停执行),以减慢线程。当线程睡眠时,它睡在某个地方,在它苏醒之前不会返回到可运行状态。当睡眠时间到了,则该线程返回到可运行状态。

线程睡眠的原因:线程执行太快,或者需要强制进入下一轮,因为Java规范不保证合理的轮换。

睡眠的位置:为了让其他线程有机会执行,可以将Thread.sleep()的调用放线程run()之内。这样才能保证该线程执行过程中会睡眠。

看下面的例子:

public class SleepDemo {    public static void main(String[] args) {        Thread thread = new Thread(new My_thread());        thread.setName("my_thread");        thread.start();        for (int i = 0; i < 10; i++) {            System.out.println(Thread.currentThread().getName() + "-------->" + i);            try {                Thread.sleep(100);            } catch (InterruptedException e) {                e.printStackTrace();            }        }    }}class My_thread implements Runnable {    @Override    public void run() {        for (int i = 0; i < 10; i++) {            System.out.println(Thread.currentThread().getName() + "-------->" + i);            try {                Thread.sleep(100);            } catch (InterruptedException e) {                e.printStackTrace();            }        }    }}

输出结果:

my_thread-------->0main-------->0main-------->1my_thread-------->1main-------->2my_thread-------->2main-------->3my_thread-------->3main-------->4my_thread-------->4main-------->5my_thread-------->5main-------->6my_thread-------->6my_thread-------->7main-------->7main-------->8my_thread-------->8main-------->9my_thread-------->9
main-------->0my_thread-------->0main-------->1my_thread-------->1main-------->2my_thread-------->2main-------->3my_thread-------->3main-------->4my_thread-------->4my_thread-------->5main-------->5main-------->6my_thread-------->6my_thread-------->7main-------->7main-------->8my_thread-------->8main-------->9my_thread-------->9

这样在每次执行过程中,总会睡眠,睡眠了,其他线程就会有执行机会了。

注意:
1、线程睡眠是帮助所有线程获得运行机会的最好方法。
2、线程睡眠到期自动苏醒,并返回到可运行状态,不是运行状态。因此,sleep()方法不能保证该线程睡眠到期后就开始执行。
3、sleep()是静态方法,只能控制当前正在运行的线程。

3. 线程优先级和线程让步yield()

线程的让步是通过Thread.yield()来实现的。yield()方法的作用是:暂停当前执行的线程,并执行其他线程。

yield()应该实现的是让当前运行线程回到可运行状态,然后允许其他具有相同优先级的线程获得运行机会。所以使用yield()的目的是让相同优先级的线程之间的轮转执行。但是在实际中无法保证yield()达到让步的目的,因为让步的线程还有可能再次被CPU选中。

结论:yield()从未导致线程转到等待/睡眠/阻塞状态。在大多数情况下,yield()将导致线程从运行状态转到可运行状态,但有可能没有效果。

以下实现代码:

public class JoinDemo implements Runnable {    @Override    public void run() {        // TODO Auto-generated method stub        for(int i=0; i<5; i++){            Thread.yield();            System.out.println(Thread.currentThread().getName()+"-------->"+i);        }    }    public static void main(String[] args) {        JoinDemo demo1 = new JoinDemo();        JoinDemo demo2 = new JoinDemo();        Thread thread1 = new Thread(demo1, "A");        Thread thread2 = new Thread(demo2, "B");        thread1.start();        thread2.start();    }}

执行结果:

A-------->0A-------->1B-------->0B-------->1B-------->2B-------->3B-------->4A-------->2A-------->3A-------->4

4. join()方法

Thread的非静态方法join()让一个线程B“加入”到另外一个线程A的尾部。在A执行完毕之前,B不能工作。

另外,join()方法还有带超时限制的重载版本。 例如t.join(5000);则让线程等待5000毫秒,如果超过这个时间,则停止等待,变为可运行状态。

例如:

public class JoinDemo implements Runnable {    @Override    public void run() {        // TODO Auto-generated method stub        for(int i=0; i<10; i++){            try {                Thread.sleep(100);            } catch (InterruptedException e) {                e.printStackTrace();            }            System.out.println(Thread.currentThread().getName()+"-------->"+i);        }    }    public static void main(String[] args) throws InterruptedException {        JoinDemo demo1 = new JoinDemo();        Thread thread1 = new Thread(demo1, "A");        thread1.start();        thread1.join();        for(int i=0; i<10; i++){            System.out.println(Thread.currentThread().getName()+"-------->"+i);            try {                Thread.sleep(100);            } catch (InterruptedException e) {                e.printStackTrace();            }        }    }}

运行结果:

A-------->0A-------->1A-------->2A-------->3A-------->4A-------->5A-------->6A-------->7A-------->8A-------->9main-------->0main-------->1main-------->2main-------->3main-------->4main-------->5main-------->6main-------->7main-------->8main-------->9

5. 小结

  • 到目前位置,介绍了线程离开运行状态的3种方法:
    1、调用Thread.sleep():使当前线程睡眠至少多少毫秒(尽管它可能在指定的时间之前被中断)。
    2、调用Thread.yield():不能保障太多事情,尽管通常它会让当前运行线程回到可运行性状态,使得有相同优先级的线程有机会执行。
    3、调用join()方法:保证当前线程停止执行,直到该线程所加入的线程完成为止。然而,如果它加入的线程没有存活,则当前线程不需要停止。

  • 除了以上三种方式外,还有下面几种特殊情况可能使线程离开运行状态:
    1、线程的run()方法完成。
    2、在对象上调用wait()方法(不是在线程上调用)。
    3、线程不能在对象上获得锁定,它正试图运行该对象的方法代码。
    4、线程调度程序可以决定将当前运行状态移动到可运行状态,以便让另一个线程获得运行机会,而不需要任何理由。

原创粉丝点击