一、线程的状态
从创建到消亡,线程一般包含以下几种状态:创建(new),就绪(runnable),运行(running),阻塞(blocked),waiting,time_waiting,消亡(dead)。
当需要新起一个线程去执行某个子任务的时候,线程被创建(new)。创建之后还需要JVM为其分配一些内存空间后,才会进入就绪状态(runnable)。
线程进入就绪状态后,不一定会立刻得到CPU执行时间,有可能CPU在执行其他的任务,只有获取CPU执行时间后,线程才会进入运行状态(running)。
线程在运行状态中,有可能会被其他事件打断从而暂停运行。比如,用户主动让线程等待——wating(wait(),join()),之后通过notify()、notifyAll()来唤醒或者run()执行完毕;用户让线程睡眠一定的时间后唤醒——time_wating(sleep(time),wait(time),join(time));或者线程被同步块阻塞——blocked。
当出现异常中断或者任务执行完毕后,线程消亡(dead)。
二、Thread类的方法
1.start()
线程调用start(),系统便会启动一个新的线程来执行任务,并且提供线程所需要的资源。
//mThread是Thread继承类
mThread t = new mThread();
t.start();
//也可以这样
new mThread().start();
2.run()
通过start()启动一个线程后,线程获得CPU执行时间后会自动调用继承类中的run方法,所以继承Thread类必须重写run()。
3.sleep()
sleep方法有两种版本:
sleep(long millis) //参数为毫秒
sleep(long millis,int nanoseconds) //第一参数为毫秒,第二个参数为纳秒
sleep方法相当于主动让线程睡眠,交出CPU,让CPU去执行其他的任务。
但是有一点要非常注意,sleep方法不会释放锁,也就是说如果当前线程持有对某个对象的锁,则即使调用sleep方法,其他线程也无法访问这个对象。如下例:
private int i = 10;
private Object object = new Object();
public static void main(String[] args) throws IOException {
Test test = new Test(); //Test为类名
MyThread thread1 = test.new MyThread();
MyThread thread2 = test.new MyThread();
thread1.start();
thread2.start();
}
class MyThread extends Thread{
@SuppressWarnings("static-access")
@Override
public void run() {
synchronized (object) {
i++;
System.out.println("i:"+i);
try {
System.out.println("线程"+Thread.currentThread().getId()+"进入睡眠状态");
Thread.currentThread().sleep(10000);
} catch (InterruptedException e) {
// TODO: handle exception
}
System.out.println("线程"+Thread.currentThread().getId()+"睡眠结束");
i++;
System.out.println("i:"+i);
}
}
}
运行结果如下:
从上面输出结果可以看出,当Thread-0进入睡眠状态之后,Thread-1并没有去执行具体的任务。只有当Thread-0执行完之后,此时Thread-0释放了对象锁,Thread-1才开始执行。
注意,如果调用了sleep方法,必须捕获InterruptedException异常或者将该异常向上层抛出。当线程睡眠时间满后,不一定会立即得到执行,因为此时可能CPU正在执行其他的任务。所以说调用sleep方法相当于让线程进入阻塞状态。
4.join()
join方法有三个版本:
join()
join(long millis) //参数为毫秒
join(long millis,int nanoseconds) //第一参数为毫秒,第二个参数为纳秒
假如在main线程中,调用thread.join方法,则main方法会等待thread线程执行完毕或者等待一定的时间。如果调用的是无参join方法,则等待thread执行完毕,如果调用的是指定了时间参数的join方法,则等待一定的事件。
看下面一个例子:
public static void main(String[] args) throws IOException {
System.out.println("进入线程"+Thread.currentThread().getName());
Test test = new Test(); //Test为类名
MyThread thread1 = test.new MyThread();
thread1.start();
try {
System.out.println("线程"+Thread.currentThread().getName()+"等待");
thread1.join();
System.out.println("线程"+Thread.currentThread().getName()+"继续执行");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
class MyThread extends Thread{
@SuppressWarnings("static-access")
@Override
public void run() {
System.out.println("进入线程"+Thread.currentThread().getName());
try {
Thread.currentThread().sleep(5000);
} catch (InterruptedException e) {
// TODO: handle exception
}
System.out.println("线程"+Thread.currentThread().getName()+"执行完毕");
}
}
运行结果:
可以看出,当调用thread1.join()方法后,main线程会进入等待,然后等待thread1执行完之后再继续执行。
实际上调用join方法是调用了Object的wait方法,这个可以通过查看源码得知:
wait方法会让线程进入阻塞状态,并且会释放线程占有的锁,并交出CPU执行权限。
由于wait方法会让线程释放对象锁,所以join方法同样会让线程释放对一个对象持有的锁。
5.yield()
调用yield方法会让当前线程交出CPU权限,让CPU去执行其他的线程。它跟sleep方法类似,同样不会释放锁。但是yield不能控制具体的交出CPU的时间,另外,yield方法只能让拥有相同优先级的线程有获取CPU执行时间的机会。
注意,调用yield方法并不会让线程进入阻塞状态,而是让线程重回就绪状态,它只需要等待重新获取CPU执行时间,这一点是和sleep方法不一样的。
6.interrupt()
interrupt,顾名思义,即中断的意思。单独调用interrupt方法可以使得处于阻塞状态的线程抛出一个异常,也就说,它可以用来中断一个正处于阻塞状态的线程;另外,通过interrupt方法和isInterrupted()方法来停止正在运行的线程。
看下例:
@SuppressWarnings("static-access")
public static void main(String[] args) throws IOException {
Test test = new Test(); //Test为类名
MyThread thread = test.new MyThread();
thread.start();
try {
System.out.println("线程"+Thread.currentThread().getId()+"进入2S睡眠状态");
Thread.currentThread().sleep(2000);
System.out.println("线程"+Thread.currentThread().getId()+"解除2S睡眠状态");
} catch (InterruptedException e) {
}
System.out.println("线程"+Thread.currentThread().getId()+"开始中断");
thread.interrupt();
}
class MyThread extends Thread{
@SuppressWarnings("static-access")
@Override
public void run() {
try {
System.out.println("线程"+Thread.currentThread().getId()+"进入10S睡眠状态");
Thread.currentThread().sleep(10000);
System.out.println("线程"+Thread.currentThread().getId()+"睡眠完毕");
} catch (InterruptedException e) {
System.out.println("线程"+Thread.currentThread().getId()+"得到中断异常");
}
System.out.println("线程"+Thread.currentThread().getId()+"run方法执行完毕");
}
}
运行结果:
从这里可以看出,通过interrupt方法可以中断处于阻塞状态的线程。那么能不能中断处于非阻塞状态的线程呢?看下面这个例子:
@SuppressWarnings("static-access")
public static void main(String[] args) throws IOException {
Test test = new Test(); //Test为类名
MyThread thread = test.new MyThread();
thread.start();
try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
}
thread.interrupt();
}
class MyThread extends Thread{
@Override
public void run() {
int i = 0;
while(i<Integer.MAX_VALUE){
System.out.println(i+" while循环");
i++;
}
}
}
运行该程序会发现,while循环会一直运行直到变量i的值超出Integer.MAX_VALUE。所以说直接调用interrupt方法不能中断正在运行中的线程。
但是如果配合isInterrupted()能够中断正在运行的线程,因为调用interrupt方法相当于将中断标志位置为true,那么可以通过调用isInterrupted()判断中断标志是否被置位来中断线程的执行。比如下面这段代码:
@SuppressWarnings("static-access")
public static void main(String[] args) throws IOException {
Test test = new Test(); //Test为类名
MyThread thread = test.new MyThread();
thread.start();
try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
}
thread.interrupt();
}
class MyThread extends Thread{
@Override
public void run() {
int i = 0;
while(!isInterrupted() && i<Integer.MAX_VALUE){
System.out.println(i+" while循环");
i++;
}
}
}
运行会发现,打印若干个值之后,while循环就停止打印了。
以下是关系到线程属性的几个方法:
1)getId
用来得到线程ID
2)getName和setName
用来得到或者设置线程名称。
3)getPriority和setPriority
用来获取和设置线程优先级。
4)setDaemon和isDaemon
用来设置线程是否成为守护线程和判断线程是否是守护线程。
守护线程和用户线程的区别在于:守护线程依赖于创建它的线程,而用户线程则不依赖。举个简单的例子:如果在main线程中创建了一个守护线程,当main方法运行完毕之后,守护线程也会随着消亡。而用户线程则不会,用户线程会一直运行直到其运行完毕。在JVM中,像垃圾收集器线程就是守护线程。
Thread类有一个比较常用的静态方法currentThread()用来获取当前线程。