多线程简介
同步和异步
同步方法调用一旦开始,调用者必须等到方法调用返回后,才能继续后续的行为。异步方法调用更像一个消息传递,一旦开始,方法调用就会立即返回,调用者就可以据徐后续的操作
并发和并行
并发就是多个任务交替执行,多个任务之间还是串行的。 并行是真正意思上的同时执行。
真实的并行只可能出现在多CPU系统中
临界区
临界区的资源可被多个线程使用,但是每一次,只能有一个线程来使用它,一旦临界区资源被占用,其他线程若想要这个资源,就必须等待
阻塞和非阻塞
阻塞和非阻塞通常用来形容多线程间的相互影响。一个线程占用了临界区资源,其他线程必须等待,等待会导致线程挂起,这种情况就是阻塞。
非阻塞强调没有一个线程可以妨碍其他线程执行。所有线程都会尝试不断向前执行。
死锁,饥饿,活锁
死锁: 线程间拥有彼此的需要的资源,造成互相等待的情况
饥饿: 线程优先级太低,一直抢占不到所需资源
活锁: 资源不断在两个资源间跳动,而没有一个线程可以拿到所有资源正常执行。
并发级别
-
阻塞: 线程必须等待其他其他线程释放所需的资源(等到临界区的锁),否则就必须等待。(悲观策略)
-
无饥饿: 低优先级线程产生饥饿
-
无障碍: 不会因为临界区资源而被挂起。大家一起共享数据,一旦数据被破坏,则进行回滚(乐观策略)
-
无锁: 无锁情况下,所有的线程都尝试对临界区进行访问。不同的是,无锁并发保证必然有一个线程能够在有限步内完成操作离开临界区。无锁的并行总能保证有一个线程是可以胜出的。
-
无等待: 所有的线程都必须在有限步内完成。如RCU(read-copy-update)对数据的读都是无等待的。
阻塞和饥饿属于阻塞,其他是非阻塞。
JMM特性
原子性: 操作不可中断
可见性: 一个线程中修改数据,其他线程是否能访问到
有序性: 指令重排
Java Memory Model(java 内存模型)是java虚拟机规范中定义来屏蔽掉各种硬件和操作系统的内存访问差异,以实现让JAVA程序在各种平台下都能达到一致的内存访问效果。(是对内存访问的一种抽象。
主内存和工作内存
共享的变量存在主内存,不需共享的变量则存在工作内存。 每个线程都有属于自己的工作内存,存放各自线程的变量。
JMM 的可见性
多线程的难点在于解决多线程间的数据共享和同步。
JMM如何解决可见性问题?
使用volatile修饰变量就会让变量立即可见。
当写一个volatile变量时,JMM会把该线程对应的工作内存中的共享变量值刷新到主内存中。
当读取一个volatile变量时,JMM会把该线程对应的工作内存设置为无效。(也就是是说,会从主内存中读取。)
另外,volatile作用于变量还可以禁止指令的冲排序。
java程序编译后会进行重排序指令优化已提高效率,但是在多线程环境下可能会有问题,而volatile可以禁止在其前后的重排序优化。
volatile 无法保证对变量的任何操作都是原子性。
多线程基本概念
进程和线程
进程:进程独占内存空间,让操作系统的并发行成为可能
线程:共享线程的内存资源,相互间切换更快速,线程让进程的内部并发成为可能
线程就是轻量级的进程,是程序的最小单位。线程的切换和调度成本要远小于进程。
线程创建
1. 继承Thread-》重写run方法
public class HelloThread extends Thread{
String name;
public HelloThread(String name) {
this.name = name;
}
@Override
public void run() {
for (int i = 0; i < 3 ; i++){
System.out.println("Hello:"+ name);
}
}
public static void main(String[] args) {
Thread t1 = new HelloThread("ywf");
t1.start();
for (int i = 0; i < 3; i++) {
System.out.println("Main!");
}
}
}
- 实现Runnable-》实现run方法
继承Thread和实现Runnable
Runnable 就是一个接口,接口定义了run方法
public interface Runnable {
public abstract void run();
}
Thread是个类,Thread实现了Runnable接口,Runnable接口中只有一个run方法,该接口不具有多线程的特性,多线程的特性是依赖Thread里的start方法去创建一个子线程,在子线程中去调用Thread里实现好的run方法,去执行相应的业务逻辑,才能让这个类实现多线程的特性
public class Thread implements Runnable{
private boolean daemon = false;
/* What will be run. */
private Runnable target;
//都是native方法
public static native Thread currentThread();
public static native void yield();
public static native void sleep(long millis) throws InterruptedException;
public synchronized void start() ;
@Override
public void run() {
if (target != null) {
target.run();
}
}
public Thread(Runnable target) {
init(null, target, "Thread-" + nextThreadNum(), 0);
}
public void interrupt() {
if (this != Thread.currentThread())
checkAccess();
synchronized (blockerLock) {
Interruptible b = blocker;
if (b != null) {
interrupt0(); // Just to set the interrupt flag
b.interrupt(this);
return;
}
}
interrupt0();
}
public static boolean interrupted() {
return currentThread().isInterrupted(true);
}
public boolean isInterrupted() {
return isInterrupted(false);
}
private native boolean isInterrupted(boolean ClearInterrupted);
public final void join() throws InterruptedException {
//底层是native
join(0);
}
}
可以看出Thread实现了Runnable,而大部分方法都是native的。
join方法 可以等待直到线程执行完成。
interrupted 可已设置线程的中断状态为true,仅仅是设置了状态,是否真的中断要在线程中具体实现。
线程的启动
调用线程Thread 的start方法启动线程。
- 调用start方法会创建一个新的子线程并启动,启动后会自动执行重写的run方法。
- 如果直接调用run方法是不会创建新线程的,会当成一个普通方法的调用
public synchronized void start() {
if (threadStatus != 0)
throw new IllegalThreadStateException();
group.add(this);
boolean started = false;
try {
start0();
started = true;
} finally {
}
}
start 会调用 start0 方法,该方法是一个native方法,会调用
JVM的startThread方法创建新线程
线程的状态
六个状态,源码如下
public enum State {
NEW,
RUNNABLE,
BLOCKED,
WAITING,
TIMED_WAITING,
TERMINATED;
}
查看枚举类,有6个状态.
当线程终止后,状态为TERMINATED。
线程终止的情况有:
- run方法运行结束
- 运行异常
- 调用Thread.stop()方法。 不推荐这样做
线程中断
中断并不是让线程不再执行,只是设置了中断标志位,线程能够检测到中断通知,并决定接下来的动作。
调用interupt(),设置中断标志位。
如果线程处于阻塞状态,那么线程立即退出阻塞状态,并抛出一个InterruptedException异常。
如果线程处于正常活动状态,那么线程可以执行isInterrupted()判断是否设置了中断标志,并决定是否继续执行。
public void THread.interupt() //中断线程
public boolean Thread.isInterrupted() //判断线程是否被中断
public boolean Thread.interrupted() //判断是否被中断,并清除当前中断状态
Thread.sleep()方法会由于中断而抛出异常。不是运行时异常,程序必须捕获并处理它
public class HelloInterrupt extends Thread {
@Override
public void run() {
while (!isInterrupted()) {
System.out.println("Hello");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
System.out.println("中断后处理...");
e.printStackTrace();
break;
}
}
}
public static void main(String[] args) throws InterruptedException {
HelloInterrupt t = new HelloInterrupt();
t.start();
Thread.sleep(1000);
t.interrupt();
System.out.println("Main end");
}
}
另外,我们也可以用其他变量来当 标志位,用volitale来修饰,保证线程间的可见性
public class Interrupt2 implements Runnable{
public volatile boolean flag = true;
private Runnable runnable;
@Override
public void run() {
while (flag) {
System.out.println("Hello");
try {
Thread.sleep(100);
}catch (Exception e){
System.out.println("这种方式执行不到这。。。");
}
}
}
public static void main(String[] args) throws InterruptedException {
Interrupt2 runnable = new Interrupt2();
Thread t = new Thread(runnable);
t.start();
Thread.sleep(500);
runnable.flag = false;
}
}
守护线程
有一些线程需要在程序中不断地执行,这样JVM无法退出,这时候需要将其设置为守护线程,当其他线程结束后,守护线程会自动停止
守护线程: 特俗的线程,完成一些系统性的服务。如垃圾回收线程,JIT线程可理解为守护线程
当所有用户线程结束后,守护线程会自动停止
public class DaemonThread extends Thread {
@Override
public void run() {
while (true) {
System.out.println("不停地执行");
try {
Thread.sleep(1000);
} catch (InterruptedException e){
break;
}
}
}
public static void main(String[] args) throws InterruptedException {
System.out.println("主线程开始 ");
DaemonThread t = new DaemonThread();
//setDaemon要在start方法之前执行
t.setDaemon(true);
t.start();
Thread.sleep(5000);
System.out.println("主线程结束后,守护线程会自动结束");
}
}
线程同步
synchronized关键字
synchronized 的作用是实现线程间的同步。它的工作是对同步的代码加锁,使得每一次都只有一个线程能进入同步块。
synchronized用法
指定加锁对象: 对给定对象加锁,进入同步代码前要获得给定对象的锁
//第一种,对给定对象加锁,进入同步代码前要获得给定对象的锁
public static class AccountingSync implements Runnable{
static AccountingSync instance = new AccountingSync();
static int i = 0;
@Override
public void run() {
for(int j = 0 ; j < 1000000 ; j++) {
synchronized(instance) {
System.out.println("-------------");
}
}
}
}
直接作用于实例方法: 相当于对当前实例加锁
//第二种,直接作用于实例方法:相当于给当前实例加锁,进入同步代码前要获得当前实例的锁
public static class AccountingSync2 implements Runnable{
static AccountingSync2 instance = new AccountingSync2();
static int i = 0;
public synchronized void increase() {
i++;
}
@Override
public void run() {
for(int j = 0 ; j < 100000; j++)
increase();
}
}
直接作用于静态方法: 相当于对当前类加锁
//第三种,直接作用域静态方法,相当于给当前类加锁。
public static class AccountingSync3 implements Runnable{
static AccountingSync3 instance = new AccountingSync3();
static int i = 0;
//会对当前类进行加锁
public static synchronized void increase() {
i++;
}
@Override
public void run() {
for(int j = 0 ; j < 100000; j++)
increase();
}
}
同步例子
class AddThread extends Thread{
@Override
public void run() {
for(int i = 0; i < SynchronizedTest.LOOP; i++) {
SynchronizedTest.count+=1;
}
}
}
class DecThread extends Thread {
@Override
public void run() {
for (int i = 0; i < SynchronizedTest.LOOP ; i++) {
SynchronizedTest.count--;
}
}
}
public class SynchronizedTest {
final static int LOOP = 10000;
public static int count = 0;
public static void main(String[] args) throws InterruptedException {
Thread t1 = new AddThread();
Thread t2 = new DecThread();
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(count);
}
}
运行结果并不一定是0。
多线程同时修改变量,会造成逻辑错误(操作不是原子性)
需要通过synchronized同步
同步的本质就是给指定对象加锁
注意加锁对象必须是同一个实例
对JVM定义的单个原子操作不需要同步
属于原子性的操作
-
基本类型(long和double除外)赋值
-
引用类型赋值
除此之后,其他操作需加锁
线程安全的类:
String, Integer,StringBuffer等
死锁
死锁产生的条件:
多线程各自持有不同的锁,并互相试图获取对方已持有的锁,双方无限等待下去:导致死锁
如何避免死锁:
多线程获取锁的顺序要一致
线程协同机制 wait/notify
对象实例调用wait()时,必须包含对应的synchronized语句中
当一个对象实例上调用wait方法后,当前线程就会在这个对象上等待。知道其他线程通过对象实例调用notify方法为止。
如果一个线程调用了object.wait(), 那么他就会进入object对象等待队列。当object.notify()被调用后,会从这个等待队列随机选择一个线程,并将其唤醒。
class MyQueue {
Queue<String > queue = new LinkedList<>();
public synchronized String getTask() throws InterruptedException {
while (this.queue.isEmpty()) {
this.wait();
}
return queue.remove();
}
public synchronized void addTask(String name){
this.queue.add(name);
this.notifyAll();
}
}
class WorkerThread extends Thread{
MyQueue myQueue;
public WorkerThread(MyQueue myQueue){
this.myQueue = myQueue;
}
@Override
public void run() {
while (!isInterrupted()){
String name;
try {
name = myQueue.getTask();
}catch (InterruptedException e){
break;
}
String result = "Hello, "+ name;
System.out.println(result);
}
}
}
public class TaskQueue {
public static void main(String[] args) throws InterruptedException {
MyQueue myQueue = new MyQueue();
WorkerThread t = new WorkerThread(myQueue);
t.start();
myQueue.addTask("yang");
Thread.sleep(1000);
myQueue.addTask("Alice");
Thread.sleep(1000);
myQueue.addTask("Tim");
Thread.sleep(1000);
t.interrupt();
t.join();
}
}
wait()和Sleep()的区别
wait是Object的原生方法。而Sleep是线程Thread的原生方法。 wait(time) 传入时间会自动唤醒。也可通过Object.notify()唤醒
wait() 会释放资源锁。需在同步块中使用(只有获取了锁才有可能释放锁)
Sleep()只会让出CPU,不会释放锁。
notify和notifyAll的区别
线程调用notify释放某个对象的锁,会进入等待池进行等待。
notify()方法调用会唤醒一个等待池中的线程重新进行锁的争夺。而notifyAll会将等待该对象的所有挂起的线程唤醒进行锁争夺。
线程让步 yield
当调用Thread。yield,会给线程调度器一个当前线程愿意让出CPU的暗示,但是线程调度器可能会忽略这个暗示。