写在前面:理解线程,我认为只要理解两个名字就行了,异步和并发;先记录一下线程的实现方式,后面会详细解释这两个词以及线程的状态
一、线程的实现
1、继承Thread类
public class ThreadDemo extends Thread {
@Override
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread - 1");
}
public static void main(String[] args) {
new ThreadDemo().start();
System.out.println("main - 1");
}
}
2、实现Runnable接口
public class RunnableDemo implements Runnable {
@Override
public void run() {
// false
//System.out.println(Thread.currentThread().isInterrupted());
// 外部中断线程的标记位
while(!Thread.currentThread().isInterrupted()) {
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("test");
}
}
public static void main(String[] args) {
Thread thread = new Thread(new RunnableDemo());
thread.start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 修改标志位,,如果捕获了InterruptedException这个异常
// 会响应改异常做复位
thread.interrupt();
// true
System.out.println(thread.isInterrupted());
}
}
上面的interrupt()是线程的标志位操作,调用该方法会改变标志位的值
3、实现Callable接口,带返回值的线程
public class CallableDemo implements Callable<String> {
public String call() throws Exception {
return "SUCCESS";
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(1);
Future<String> future = executorService.submit(new CallableDemo());
System.out.println("开始阻塞");
System.out.println(future.get());
}
}
大家所熟悉的restTemplate请求时就是通过该线程方式实现的优化,异步发送请求拿到返回值
二、线程的状态
1、先看一段代码
public class ThreadStatus {
public static void main(String[] args) {
// 阻塞状态 TIMED_WAITING
new Thread(()->{
while (true){
try {
TimeUnit.SECONDS.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"STATUS-01").start();
// 阻塞状态 WAITING
new Thread( () -> {
while(true) {
synchronized (ThreadStatus.class) {
try {
ThreadStatus.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}, "STATUS-02").start();
// TIMED_WAITING
new Thread(new BlockDemo(), "Block-01").start();
//BLOCKED
new Thread(new BlockDemo(), "Block-02").start();
}
static class BlockDemo extends Thread {
@Override
public void run() {
synchronized (BlockDemo.class) {
while (true){
try {
TimeUnit.SECONDS.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
在idea工具里面运行该代码,找到.class文件,打开命令窗口,输入jps查找进程号3928,如下
继续运行命令 jstack 3928,可以看到代码中各进程的状态,如下:
如下为线程生命周期
最后: