Thread状态: New, 线程刚刚创建,还没执行
Runnable, 就绪,资源准备好了
Blocked, 遇到synchronized, 进入阻塞暂停执行,等待获取锁.
Waiting, 无时间限制的等待, 一般是在等待notify() , join()方法则是等待目标线程终止.
TIme-Waiting,
Terminated; 结束
java操作线程的基本API:
1. 新建线程
public class CreateThreads implements Runnable{ @Test public void method1() { Thread t1 = new Thread() { @Override public void run() { System.out.println("I am fine!"); } }; t1.start(); } @Override public void run() { System.out.println("I am runnable"); } public static void main(String[] args) { Thread thread = new Thread(new CreateThreads()); thread.start(); } }
2 .停止
stop()可以将一个线程直接退出, 强行终止线程容易导致数据不一致.
例如: 数据写入一半, stop()结束线程, 释放当前线程持有的锁, 另一个线程持锁读到这个数据并改动.
自定义线程停止: 一个volatile变量, 改变变量的方法, 停止逻辑.
3.,中断线程
线程中断是很重要的线程协作机制,
public class InterruptThread {
/**
* interrupt() 中断线程, 只是提供了一个提示信息, 如何退出自己决定 , 如果立即无条件退出等同于stop()
* isInterrupted() 判断是否中断
* interrupted() 判断是否中断,并且清除中断状态
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread() {
@Override
public void run() {
//自定义退出逻辑
while (Thread.currentThread().isInterrupted()) {
System.out.println("exit interrupt");
break;
}
Thread.yield();
}
};
thread.start();
thread.interrupt();
}
/**
* sleep()会让线程休眠若干时间并进入阻塞状态,并不会放开锁,也就是说如果有synchronized同步块,其他线程仍然不能访问共享数据。遇到中断会抛出异常
* @throws InterruptedException
*/
@Test
public void test2() throws InterruptedException {
Thread thread = new Thread() {
@Override
public void run() {
while (true) {
if(Thread.currentThread().isInterrupted()) {
//第二次循环,检查到中断,跳出循环
System.out.println("interrupted");
break;
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
System.out.println("Interrupted in sleep");
//第二次中断
Thread.currentThread().interrupt();
}
Thread.yield();
}
}
};
thread.start();
Thread.sleep(2000);
//第一次中断, 此时线程在try部分, 异常触发再次添加中断
thread.interrupt();
}
}