Java多线程总结(二):线程阻塞与线程控制

一. 线程阻塞与线程控制

1.join()
join的作用是让一个线程等待另一个线程执行完后再继续执行。如A线程线程执行体中调用B线程的join()方法,则A线程被阻塞,直到B线程执行完为止,A才能得以继续执行。下面看个例子:

public class MethodJonin {

    public static void main(String[] args) {
        Myrunnable myrunnable = new Myrunnable();
        Thread thread = new Thread(myrunnable);
        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName() + " " + i);
            if (i == 3) {
                thread.start();
                try {
                    thread.join();    // main线程需要等待thread线程执行完后才能继续执行
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

class Myrunnable implements Runnable {
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName() + " " + i);
        }
    }
}

上面例子中,在main方法循环时符合i==3条件后启动myrunnable实现的线程,并调用了此线程的join方法。那么main方法需要等待新启动的线程执行完后再执行,结果如下:

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

2.sleep()方法
sleep方法让当前线程暂停至指定之间,并使线程处于阻塞状态。在线程睡眠的时间段内,由于线程不是可执行状态,所以该线程不会得到执行机会,即使此时系统中没有任何其他可执行的线程。sleep()常用来暂停线程。
前面有讲到,当调用了新建的线程的start()方法后,线程进入到就绪状态,可能会在接下来的某个时间获取CPU时间片得以执行,如果希望这个新线程必然性的立即执行,直接调用原来线程的sleep(1)即可。

public class MethodSleep {
    public static void main(String[] args) {

        MyRunnableSleep myRunnable = new MyRunnableSleep();
        Thread thread = new Thread(myRunnable);

        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName() + " " + i);
            if (i == 3) {
                thread.start();
                try {
                    Thread.sleep(1);   // 使得thread必然能够马上得以执行
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

class MyRunnableSleep implements Runnable {
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName() + " " + i);
        }
    }
}

3.后台线程(Daemon Thread)
概念/目的:后台线程主要是为其他线程(相对可以称之为前台线程)提供服务,或“守护线程”。如JVM中的垃圾回收线程。

生命周期:后台线程的生命周期与前台线程生命周期有一定关联。主要体现在:当所有的前台线程都进入死亡状态时,后台线程会自动死亡(其实这个也很好理解,因为后台线程存在的目的在于为前台线程服务的,既然所有的前台线程都死亡了,那它自己还留着有什么用…伟大啊 ! !)。

设置后台线程:调用Thread对象的setDaemon(true)方法可以将指定的线程设置为后台线程。

public class DaemonThread {
    public static void main(String[] args) {
        Thread myThread = new MyThread();
        for (int i = 0; i < 10; i++) {
            System.out.println("main thread i = " + i);
            if (i == 2) {
                myThread.setDaemon(true);
                myThread.start();
            }
        }
    }
}
class MyThread extends Thread {
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("i = " + i);
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

判断线程是否是后台线程:调用thread对象的isDeamon()方法。

注:main线程默认是前台线程,前台线程创建中创建的子线程默认是前台线程,后台线程中创建的线程默认是后台线程。调用setDeamon(true)方法将前台线程设置为后台线程时,需要在start()方法调用之前。前台线程都死亡后,JVM通知后台线程死亡,但从接收指令到作出响应,需要一定的时间。

4.改变线程的优先级/setPriority()
每个线程在执行时都具有一定的优先级,优先级高的线程具有更多的执行机会。每个线程默认的优先级都与创建它的线程的优先级相同。main线程默认具有普通优先级。
设置线程优先级:setPriority(int priorityLevel)。参数priorityLevel范围在1-10之间,常用的有如下三个静态常量值:

MAX_PRIORITY:10

MIN_PRIORITY:1

NORM_PRIORITY:5

获取线程优先级:getPriority()。

注:具有较高线程优先级的线程对象仅表示此线程具有较多的执行机会,而非优先执行。

public class ThreadPriority {
    public static void main(String[] args) {
        Thread myThread = new MyThreadPriority();
        for (int i = 0; i < 10; i++) {
            System.out.println("main thread i = " + i);
            if (i == 2) {
                myThread.setPriority(Thread.MAX_PRIORITY);
                myThread.start();
            }
        }
    }
}


class MyThreadPriority extends Thread {

    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("i = " + i);
        }
    }
}

5.线程让步:yield()
上一篇博文中已经讲到了yield()的基本作用,同时,yield()方法还与线程优先级有关,当某个线程调用yiled()方法从运行状态转换到就绪状态后,CPU从就绪状态线程队列中只会选择与该线程优先级相同或优先级更高的线程去执行。

public class MethodYield {
    public static void main(String[] args) {
        Thread myThread1 = new Mythread1();
        Thread myThread2 = new MyThread2();
        myThread1.setPriority(Thread.MAX_PRIORITY);
        myThread2.setPriority(Thread.MIN_PRIORITY);

        for (int i = 0; i < 10; i++) {
            System.out.println("main thread i = " + i);
            if (i == 2) {
                myThread1.start();
                myThread2.start();
                Thread.yield();
            }
        }
    }
}

class Mythread1 extends Thread {
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("myThread 1 --  i = " + i);
        }
    }
}

class MyThread2 extends Thread {
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("myThread 2 --  i = " + i);
        }
    }
} 

参考文章
http://www.cnblogs.com/lwbqqyumidi/p/3817517.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值