1. 概念
在维基百科中解释道
多线程(英语:multithreading),是指从软件或者硬件上实现多个线程并发执行的技术。具有多线程能力的计算机因有硬件支持而能够在同一时间执行多于一个线程,进而提升整体处理性能。具有这种能力的系统包括对称多处理机、多核心处理器以及芯片级多处理(Chip-level multithreading)或同时多线程(Simultaneous multithreading)处理器。
2. 作用
- 上面定义中看出,在硬件的支持下,在同一时间运行多线程,能够提升处理器的性能。现在大部分电脑都是多核cpu,充分利用多核的资源。
- 防止线程阻塞,如果是单线程,如果一个线程停止,则会影响后面的进程的运行,导致线程阻塞。
3. 使用
3.1 线程周期
-
新建状态,当程序使用new关键字创建了一个线程之后,该线程就处于新建状态,此时仅由JVM为其分配内存,并初始化其成员变量的值
-
就绪状态,当线程对象调用了start()方法之后,该线程处于就绪状态。Java虚拟机会为其创建方法调用栈和程序计数器,等待调度运行
-
运行状态,如果处于就绪状态的线程获得了CPU,开始执行run()方法的线程执行体,则该线程处于运行状态
-
阻塞状态,当处于运行状态的线程失去所占用资源之后,便进入阻塞状态
-
在线程的生命周期当中,线程的各种状态的转换过程
3.3 线程创建
/**
* 线程创建第一种方式
* 1. 继承Thread
*/
public class MyThread extends Thread{
@Override
public void run() {
System.out.println("线程的第一次种创建方式");
}
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.run();
}
}
/**
* 线程创建第二种方式
* 1. 实现Runnable接口
*/
class MyThread2 implements Runnable {
@Override
public void run() {
System.out.println("线程创建的第二种方式");
}
public static void main(String[] args) {
MyThread2 thread = new MyThread2();
thread.run();
}
}
/**
* 线程创建第三种方式
* 1. 实现Callable接口
* 2. 创建futureTask实例,用Callable作为参数
*
* @param <T>
*/
class MyCallable<T> implements Callable<T> {
@Override
public T call() throws Exception {
System.out.println("线程创建的第三种方式");
return null;
}
public static void main(String[] args) {
FutureTask futureTask =new FutureTask<>(new MyCallable<>());
Thread thread = new Thread(futureTask);
thread.run();
}
}
3.4 关闭线程
stop()
这里stop() jdk中是不推荐使用的,官方的解释
@deprecated This method is inherently unsafe. Stopping a thread with
* Thread.stop causes it to unlock all of the monitors that it
* has locked (as a natural consequence of the unchecked
*ThreadDeath
exception propagating up the stack). If
* any of the objects previously protected by these monitors were in
* an inconsistent state, the damaged objects become visible to
* other threads, potentially resulting in arbitrary behavior. Many
* uses ofstop
should be replaced by code that simply
* modifies some variable to indicate that the target thread should
* stop running. The target thread should check this variable
* regularly, and return from its run method in an orderly fashion
* if the variable indicates that it is to stop running. If the
* target thread waits for long periods (on a condition variable,
* for example), theinterrupt
method should be used to
* interrupt the wait.
废弃的原因:这个方法是不安全的,stop 会解除所有的监视的锁
代替:应该用线程中断来处理interrupt
Thread thread = new Thread(() -> {
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("run...");
}
});
thread.start();
try {
Thread.sleep(5000);
thread.stop();
} catch (InterruptedException e) {
e.printStackTrace();
}
3.5 线程中断
- 通过interrupt()方法优雅的终止进程
Thread thread = new Thread(() -> {
while (true) {
//判断当前进程是否被中断
if (Thread.currentThread().interrupted()) {
break;
}
try {
//此处加上会出现异常
// Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
//设置中断状态 ,因为抛出异常会取消中断状态
Thread.currentThread().interrupt();
}
System.out.println("run...");
}
});
thread.start();
try {
Thread.sleep(5000);
//中断进程
thread.interrupt();
} catch (InterruptedException e) {
e.printStackTrace();
}
在测试的过程遇到一个异常,进程还在继续运行,判断进程是否中断失败,这个异常是使用sleep()方法抛出的,原因是线程在睡眠的时候,有人在中断,抛出的异常,给出反馈做一些处理。
所以在异常catch中必须重新设置中断
run...
run...
run...
run...
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at KillThread.lambda$main$0(KillThread.java:10)
at java.lang.Thread.run(Thread.java:745)
run...
run...
run...
run...
run...
- suspend方法挂起线程,需要通过resume解除,继续执行程序
- suspend 不会释放锁
- 如果锁发生在resume之前,会出现死锁
3.6 yeid()
what: Yield告诉当前正在执行的线程把运行机会交给线程池中拥有相同优先级的线程。
why : 能使一个线程从运行状态转到可运行状态,而不是等待或阻塞状态。
3.7 join()
what: 使得一个线程在另一个线程结束后再执行
3.8 守护线程
what:JVM实例中尚存任何一个非守护线程没有结束,守护线程就全部工作;只有当最后一个非守护线程结束是,守护线程随着JVM一同结束工作
why: 为其他线程提供便利服务,守护线程最典型的应用就是GC(垃圾回收器),他就是一个很称职的守护者。