1、线程状态
(1)new
(2)Runnable
(3)blocking synchronized或者lock使用出现的状态
(4)waiting wait notify出现的状态
(5)time waiting sleep出现的状态
一般在开发应用中,利用jstack打印的线程信息显示上述状态,这些状态可以帮忙定位相应的问题。
2、创建线程的方法
(1)Runnable创建
(2)Callable创建
(3)Thread继承
public static void main(String[] args) throws ExecutionException, InterruptedException {
//使用Runnable创建
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(20);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("aaaaa");
}
});
thread.start();
//使用Callable创建
FutureTask<Integer> futureTask = new FutureTask<Integer>(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
try {
Thread.sleep(20);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("aaaaa");
return 1;
}
});
Thread thread2 = new Thread(futureTask);
thread2.start();
System.out.println(futureTask.get());
//使用继承Thread方法创建
MyThread myThread = new MyThread();
myThread.start();
}
static class MyThread extends Thread {
@Override
public void run() {
try {
Thread.sleep(20);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("bbb");
}
}
3、线程中断
中断 顾名思义就是在程序运行过程,发生异常提前终止。
当一个线程调用interrupt方法时,如果此时这个线程处于阻塞、限期等待或者无限期等待时,会抛出InterruptedException,提前结束程序。但是不能中断I/O阻塞和synchronized锁阻塞。
那么阻塞、无限期等待或者限期等待是什么呢? 即 join、wait、sleep方法。
sleep中断例子:
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("aaa");
}
});
t1.start();
System.out.println("bbb");
t1.interrupt();
join例子:
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("aaa");
}
});
t1.start();
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
try {
t1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t2.start();
t2.interrupt();
答案是t2出现中断。
wait例子
Object object = new Object();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("bbbb");
synchronized (object) {
object.notify();
}
}
});
t1.start();
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
try {
synchronized (object) {
object.wait();
}
System.out.println("aaaaaa");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t2.start();
t2.interrupt();
答案是t2出现中断
当然除了上述程序中有这些阻塞方法外还有其他方法可以中断程序,比如在程序中增加判断方法,利用interrupted() 方法来判断线程是否处于中断状态。
总结:
以上3个基础是面试过程中常见的面试题,当然,理解这些,是为了更好的定为我们遇到的问题还有更好的编写出高质量的代码。