线程的基本状态
- 新建(New)
- 就绪(Runnable)
- 运行中
- 阻塞(Blocked)
- 死亡(Dead)
阻塞的几种场景:
- 调用sleep进入休眠状态(可中断)
- 通过wait使线程挂起(可中断)
- 任务在等待某个输入输出完成(不可中断)
- 任务尝试获取某个对象的锁,但是这个锁被其他线程占用中(不可中断)
线程启动start
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程1运行");
}
});
thread1.start();
线程终止join
说它是终止线程可能不是很准确,join的含义是:t.join()方法只会使主线程进入等待池并等待t线程执行完毕后才会被唤醒。并不影响同一时刻处在运行状态的其他线程。
public class Main {
public static void main(String[] args) throws InterruptedException {
Thread1 thread1 = new Thread1();
Thread2 thread2 = new Thread2();
thread1.start();
//thread1.join();
thread2.start();
}
}
class Thread1 extends Thread{
public void run(){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程1运行");
}
}
class Thread2 extends Thread{
public void run(){
System.out.println("线程2运行");
}
}
结果为:
线程2运行
线程1运行
Process finished with exit code 0
如果不注释thread1.join(); 结果为:
线程1运行
线程2运行
Process finished with exit code 0
注意,join后,线程还是可以被中断的。
如下:thread1 运行中启动了thread2 并进行join,thread2 运行过程中中断它,是可以中断的。
public class Main {
public static void main(String[] args) throws InterruptedException {
Thread2 thread2 = new Thread2();
Thread1 thread1 = new Thread1(thread2);
thread1.start();
thread2.interrupt();
//thread1.join();
//thread2.start();
}
}
class Thread1 extends Thread{
Thread2 thread2;
Thread1(Thread2 thread2){
this.thread2 = thread2;
thread2.start();
}
public void run(){
try {
System.out.println("线程2在线程1中join");
thread2.join();
} catch (InterruptedException e) {
System.out.println("join被中断");
}
System.out.println("线程1运行");
}
}
class Thread2 extends Thread{
public void run(){
try {
sleep(5000);
System.out.println("sleep中断后的任务不会进行");
} catch (InterruptedException e) {
System.out.println("sleep被中断");
}
System.out.println("线程2运行");
}
}
线程睡眠sleep
可被中断,不会释放锁
sleep(5000);
Thread.sleep(1000);
线程等待唤醒wait
可被中断,会释放锁
public class Main {
public static void main(String[] args) throws InterruptedException {
W w = new W();
Thread2 thread2 = new Thread2(w);
Thread1 thread1 = new Thread1(w);
thread1.start();
thread2.start();
}
}
class Thread1 extends Thread{
W w;
Thread1(W w){
this.w = w;
}
public void run(){
synchronized (w){
System.out.println("第一步");
try {
while(w.change == false) {
//注意这里必须是w.wait(),如果只是wait()那么会报错
w.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("第三步");
}
}
}
class Thread2 extends Thread{
W w;
Thread2(W w){
this.w = w;
}
public void run(){
synchronized (w){
System.out.println("第二步");
w.change = true;
w.notifyAll();
}
}
}
class W{
boolean change = false;
}
线程唤醒notify
//唤醒所有的等待线程,它们会竞争同一个锁
w.notifyAll();
//众多等待的线程中只有一个可以被唤醒
w.notify();
线程中断interrupt
中断线程
//中断线程
thread2.interrupt();
//中断标志
thread2.isInterrupted()