线程
一条线程指的是进程中一个单一顺序的控制流,一个进程中可以并发多个线程,每条线程并行执行不同的任务。多线程是多任务的一种特别的形式,但多线程使用了更小的资源开销。
一个进程包括由操作系统分配的内存空间,包含一个或多个线程。一个线程不能独立的存在,它必须是进程的一部分。一个进程一直运行,直到所有的非守护线程都结束运行后才能结束。
多线程能满足程序员编写高效率的程序来达到充分利用 CPU 的目的。
线程的生命周期
- 新建状态:使用 new 关键字和 Thread 类或其子类建立一个线程对象后,该线程对象就处于新建状态。它保持这个状态直到程序 start() 这个线程。
- 就绪状态:当线程对象调用了start()方法之后,该线程就进入就绪状态。就绪状态的线程处于就绪队列中,要等待JVM里线程调度器的调度。
- 运行状态:如果就绪状态的线程获取 CPU 资源,就可以执行 run(),此时线程便处于运行状态。处于运行状态的线程最为复杂,它可以变为阻塞状态、就绪状态和死亡状态。
- 阻塞状态:如果一个线程执行了sleep(睡眠)、suspend(挂起)等方法,失去所占用资源之后,该线程就从运行状态进入阻塞状态。在睡眠时间已到或获得设备资源后可以重新进入就绪状态。可以分为三种:
(1)等待阻塞:运行状态中的线程执行 wait() 方法,使线程进入到等待阻塞状态。
(2)同步阻塞:线程在获取 synchronized 同步锁失败(因为同步锁被其他线程占用)。
(3)其他阻塞:通过调用线程的 sleep() 或 join() 发出了 I/O 请求时,线程就会进入到阻塞状态。当sleep() 状态超时,join() 等待线程终止或超时,或者 I/O 处理完毕,线程重新转入就绪状态。 - 死亡状态:一个运行状态的线程完成任务或者其他终止条件发生时,该线程就切换到终止状态。
优先级
Java线程的优先级是一个整数,范围是1(Thread.MIN_PRIORITY )~ 10(Thread.MAX_PRIORITY )。默认为5。
线程创建的三种方法
- 继承Thread类。继承类必须重写 run() 方法。
public class test{
public static void main(String[] args) {
Thread thread1 = new GuessANumber(27, "线程1");
thread1.start();
try {
thread1.join(); // 主线程会等待该线程执行结束才继续执行
}catch(InterruptedException e) {
System.out.println("Thread interrupted.");
}
System.out.println("Starting thread4...");
Thread thread2 = new GuessANumber(75, "线程2");
thread2.start();
System.out.println("main() is ending...");
}
}
class GuessANumber extends Thread {
private int number;
public GuessANumber(int number, String name) {
this.number = number;
this.setName(name);
}
public void run() {
int counter = 0;
int guess = 0;
do {
guess = (int) (Math.random() * 100 + 1);
System.out.println(this.getName() + " guesses " + guess);
counter++;
} while(guess != number);
System.out.println("** Correct!" + this.getName() + " in " + counter + " guesses.**");
}
}
- 实现Runnable接口,传入给Thread对象并执行
public class test{
public static void main(String[] args) {
Thread t1 = new Thread(new MyRunnable(), "线程1");
Thread t2 = new Thread(new MyRunnable(), "");
t2.setName("线程2");
t2.setPriority(1); // 1最低,10最高,默认5
t2.setDaemon(true); // 设置守护线程
t1.start();
t2.start();
}
}
class MyRunnable implements Runnable {
public void run() {
String threadName = Thread.currentThread().getName();
try {
for (int i = 0; i < 50; i++) {
System.out.println("MyThread " + threadName + ": " + i);
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");
} finally {
System.out.println("Thread " + threadName + " exiting.");
}
}
}
- 实现Callable接口(多用于线程池)
import java.util.concurrent.*;
public class test{
public static void main(String[] args) throws Exception {
// 有返回值,会抛出异常
Callable<Integer> c = new Callable<Integer>() {
@Override
public Integer call() throws Exception {
System.out.println(Thread.currentThread().getName() + "...");
int sum = 0, max = (int)(Math.random() * 100);
for (int i = 0; i < max; i++) {
sum += i;
}
return sum;
}
};
// 要将Callable对象转换成可执行任务
FutureTask<Integer> task1 = new FutureTask<>(c);
FutureTask<Integer> task2 = new FutureTask<>(c);
Thread t1 = new Thread(task1);
t1.start();
Thread t2 = new Thread(task2);
t2.start();
// 获取返回值(等待call执行完毕,才会返回)
System.out.println("Result: " + task1.get());
System.out.println("Result: " + task2.get());
}
}
三种方法对比
- 采用实现 Runnable、Callable 接口的方式创建多线程时,线程类只是实现了 Runnable 接口或 Callable 接口,还可以继承其他类。
- 使用继承 Thread 类的方式创建多线程时,编写简单,如果需要访问当前线程,则无需使用 Thread.currentThread() 方法,直接使用 this 即可获得当前线程。
线程安全
- 同步代码块:为方法中的局部代码加锁,其他试图访问该对象的线程将被阻塞。
class Ticket implements Runnable {
private static int ticketNum = 0;
public void run() {
while (true) {
synchronized (this) {
if (ticketNum >= 100)
break;
System.out.println(Thread.currentThread().getName() + "卖出票" + ticketNum++);
}
}
}
}
- 同步方法:为方法中的所有代码加锁
class Ticket implements Runnable {
private static int ticketNum = 0;
public void run() {
while (sale());
}
public synchronized boolean sale() {
if (ticketNum >= 100)
return false;
System.out.println(Thread.currentThread().getName() + "卖出票" + ticketNum++);
return true;
}
}
死锁
线程死锁是指两个或两个以上的线程互相持有对方所需要的资源,由于synchronized的特性,一个线程持有一个资源,或者说获得一个锁,在该线程释放这个锁之前,其它线程是获取不到这个锁的,而且会一直死等下去,因此这便造成了死锁。
- 互斥条件:一个资源,或者说一个锁只能被一个线程所占用,当一个线程首先获取到这个锁之后,在该线程释放这个锁之前,其它线程均是无法获取到这个锁的。
- 占有且等待:一个线程已经获取到一个锁,再获取另一个锁的过程中,即使获取不到也不会释放已经获得的锁。
- 不可剥夺条件:任何一个线程都无法强制获取别的线程已经占有的锁
- 循环等待条件:线程A拿着线程B的锁,线程B拿着线程A的锁。
public class DeadLock {
private final Object lock1 = new Object(), lock2 = new Object();
public void method1() throws InterruptedException {
synchronized(lock1){
System.out.println(Thread.currentThread().getName() + "获取到lock1,请求获取lock2....");
Thread.sleep(1000);
synchronized (lock2){
System.out.println("获取到lock2....");
}
}
}
public void method2() throws InterruptedException {
synchronized(lock2){
System.out.println(Thread.currentThread().getName() + "获取到lock2,请求获取lock1....");
Thread.sleep(1000);
synchronized (lock1){
System.out.println("获取到lock1....");
}
}
}
public static void main(String[] args) {
DeadLock deadLock = new DeadLock();
Thread t1 = new Thread(()-> {
try {
deadLock.method1();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread t2 = new Thread(()-> {
try {
deadLock.method2();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("主线程结束...");
}
}
/*
Thread-0获取到lock1,请求获取lock2....
Thread-1获取到lock2,请求获取lock1....
*/
死锁处理
避免死锁:线程按照相同的顺序加锁。
死锁检测
- 使用 jps -l,查看正在运行的虚拟机进程
- 使用 jstack + id 进行跟踪排查
>> jps -l
11344 sun.tools.jps.Jps
12972 org.jetbrains.jps.cmdline.Launcher
7052 test
8540
>> jstack 7052
Java stack information for the threads listed above:
===================================================
"Thread-1":
at test.method2(test.java:19)
- waiting to lock <0x00000000db106d38> (a java.lang.Object)
- locked <0x00000000db106d48> (a java.lang.Object)
at test.lambda$main$1(test.java:36)
at test$$Lambda$2/1096979270.run(Unknown Source)
at java.lang.Thread.run(Thread.java:748)
"Thread-0":
at test.method1(test.java:9)
- waiting to lock <0x00000000db106d48> (a java.lang.Object)
- locked <0x00000000db106d38> (a java.lang.Object)
at test.lambda$main$0(test.java:29)
at test$$Lambda$1/1324119927.run(Unknown Source)
at java.lang.Thread.run(Thread.java:748)
Found 1 deadlock.
锁Lock
Lock接口与synchronized相比,显式定义,结构更灵活,提供更多实用性方法,功能更强大,性能更优越
ReentrantLock重入锁
与synchronized一样具有互斥锁功能
class MyList {
private Lock locker = new ReentrantLock();
private String[] str = {"A", "", "", ""};
private int count = 1;
public void add(String value) {
locker.lock();
try {
str[count++] = value;
} finally {
locker.unlock();
}
}
}
ReentrantReadWriteLock读写锁
支持一写多读的同步锁,读写分离,可分别分配读锁和写锁;支持多次分配读锁,使多个读操作可以并发执行。
class MyClass {
ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
ReadLock readLock = rwl.readLock();
WriteLock writeLock = rwl.writeLock();
private int value;
public int getValue() throws Exception {
readLock.lock();
try {
return value;
} finally {
readLock.unlock();
}
}
public void setValue(int value) throws Exception {
writeLock.lock();
try {
this.value = value;
} finally {
writeLock.unlock();
}
}
}
线程间通信
- wait(long timeout) 调用obj.wait()时,线程会释放其拥有的所有锁标记,同时阻塞在等待队列中。timeout为最大等待时间,默认为0(直到其他线程调用此对象的 notify() 或notifyAll()才释放)
- notify() 唤醒单个线程
- notifyAll() 唤醒所有的线程
线程池
单个线程约占1MB空间,过多分配容易造成内存溢出。频繁的创建和销毁线程会增加虚拟机回收频率,资源开销,造成程序性能下降。
线程池是线程容器,可设定线程分配的数量上限;将预先创建的线程对象存入池中,并重用线程池中的线程对象,可以避免频繁创建和销毁线程。
创建线程池
线程池接口ExecutorService 、工具类Executors
- newSingleThreadExecutor
创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。 - newFixedThreadPool
创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。 - newScheduledThreadPool
创建一个可定期或者延时执行任务的定长线程池,支持定时及周期性任务执行。 - newCachedThreadPool
创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。
ExecutorService es = Executors.newFixedThreadPool(4);
// ExecutorService es = Executors.newCachedThreadPool();
// ExecutorService es = Executors.newSingleThreadExecutor();
// ExecutorService es = Executors.newScheduledThreadPool(4);
Runnable r = new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++)
System.out.println(Thread.currentThread().getName() + ": " + i);
}
};
for (int i = 0; i < 4; i++)
es.submit(r);
es.shutdown();
线程安全的集合
- CopyOnWriteArrayList
线程安全的ArrayList,加强版的读写分离;写有锁,读无锁,读写之间不阻塞;写入时,先copy一个容器副本,添加新元素后在替换引用,使用的内存多
List<String> list = new CopyOnWriteArrayList<String>();
list.add("hello");
System.out.println(list.get(0));
- CopyOnWriteArraySet
线程安全的Set,底层使用CopyOnWriteArrayList实现
Set<String> set = new CopyOnWriteArraySet<>();
set.add("hello");
- ConcurrentLinkedQueue
线程安全、可高效读写的队列,高并发下性能最好的队列;使用无锁、CAS比较交换算法,修改的方法包含三个核心参数(V要更新的变量,E预期值,N新值)
ConcurrentLinkedQueue<Integer> queue = new ConcurrentLinkedQueue<>();
Thread t = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
queue.offer(i);
}
}
});
t.start();
t.join();
int size = queue.size();
for (int i = 0; i < size; i++) {
System.out.print(queue.poll() + " ");
}
- ArrayBlockingQueue
数组结构实现,有界队列
BlockingQueue<String> abq = new ArrayBlockingQueue<String>(5);
for (int i = 0; i < 6; i++) {
abq.put("" + i); // 数组元素个数到达5个后会阻塞,需要用take()取出元素
System.out.println(i);
}
- LinkedBlockingQueue
链表结构实现,有界队列,默认上限Integer.MAX_VALUE
BlockingQueue<String> lbq = new LinkedBlockingQueue<>(5); // 可设置容量
for (int i = 0; i < 6; i++) {
lbq.put("" + i);
System.out.println(lbq.take());
}
- ConcurrentHashMap
JDK1.7之前使用分段锁设计,JDK1.8后使用CAS
ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>();
for (int i = 0; i < 5; i++) {
new Thread(new Runnable() {
@Override
public void run() {
for (int k = 0; k < 10; k++) {
map.put(Thread.currentThread().getName() + "--" + k, "" + k);
}
}
}).start();
}