控制线程
Java的线程支持,提供了便捷工具,方便控制线程的执行。包括join线程,后台线程,线程睡眠sleep,线程让步yield,改变线程优先级prioriy。
join线程
Thread提供了让一个线程等待另一个线程完成的方法–join()。在程序执行流中调用其他线程的join()方法时,当前线程将被阻塞,直到join入来的线程执行完毕。
public class ControllThread extends Thread {
public ControllThread(String name) {
super(name);
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(this.getName() + ":" + i);
}
}
public static void main(String[] args) throws InterruptedException {
new ControllThread("新线程").start();
for (int i = 0; i < 100; i++) {
//当主线程main线程访问到的i为20时,创建和启动新线程2
if (i == 20) {
ControllThread cThread = new ControllThread("新线程2");
cThread.start();
//让新线程2加入到当前执行序列,因为是在main线程下调用,所以main线程必须等到新线程2执行完,才会往下执行
cThread.join();
}
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}
}
后台线程
守护线程,后台线程,相信各位已然熟悉。这种线程在后台运行,为其他线程提供服务,这些线程叫做Daemon Thread。JVM的垃圾回收线程就是典型的后台线程。
后台线程有个特征:
- 若所有前台线程都死亡,那么,后台线程会自动死亡。
调用Thread对象的setDaemon(true)可将线程设置为后台线程
public class DaemonThread extends Thread{
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println(getName() + ":" + i);
}
}
public static void main(String[] args) {
DaemonThread dt = new DaemonThread();
dt.setDaemon(true);
dt.start();
//main主线程去到9就结束了,后台线程可能还没执行完
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}
}
线程睡眠
如果要让当前正在执行的线程暂停一段时间,并进入阻塞状态,可以调用Thread的静态方法sleep(),常被用作暂停线程
线程让步
yield()与sleep()类似,它可以让当前线程暂停,但不会阻塞线程,
public class YieldThread extends Thread{
public YieldThread(String name){
super(name);
}
@Override
public void run() {
for (int i = 0; i < 50; i++) {
System.out.println(getName() + ":" + i);
//当i为30时,让步给相同优先级或优先级更高的线程
if(i==30){
Thread.yield();
}
}
}
public static void main(String[] args) {
YieldThread t1 = new YieldThread("高级");
t1.setPriority(MAX_PRIORITY);
t1.start();
YieldThread t2 = new YieldThread("低级");
t2.setPriority(MIN_PRIORITY);
t2.start();
}
}
线程优先级
上面代码已经显示了如果设置线程优先级。
每个线程执行时,都有一定的优先级,高的可获得更多的执行机会,反之则更少的执行机会。
每个线程默认的优先级,都与创建它的父线程的优先级相同,默认main线程有普通优先级NORMAL_PRIORITY,由main线程创建的线程也具有普通优先级。
Thread类提供了3个静态常量
/**
* The minimum priority that a thread can have.
*/
public final static int MIN_PRIORITY = 1;
/**
* The default priority that is assigned to a thread.
*/
public final static int NORM_PRIORITY = 5;
/**
* The maximum priority that a thread can have.
*/
public final static int MAX_PRIORITY = 10;