并发编程之美读书笔记 1

线程的概念

线程不能独立存在,资源由操作系统分配给进程,但是CPU资源是分配给线程的.同一个进程内的线程:

  • 共享: 堆(主要存放使用new操作创建的对象实例)和方法区(JVM加载的类,常量以及静态变量等)
  • 独立: 程序计数器(获得CPU控制权后可以从计数器指定地址继续执行)和栈区域.

当启动main函数时,就相当于启动了一个JVM的进程,而main所在的线程就是该进程中的主线程.

如何创建线程

有三种方式:

  1. 继承Thread类,重写run方法:
// Thread1.java
public class Thread1 extends Thread{

    @Override
    public void run() {
        System.out.println("current-thread: "+this.getName());
        System.out.println("继承自Thread");
    }

    public static void main(String[] args) {
        Thread1 t = new Thread1();
        t.start();
    }
}

不需要使用currentThread就可以获取当前线程,但是不能再继承其他类

  1. 实现 Runnable方法,并重写run方法:
//Thread2.java
public class Thread2 implements Runnable{
    private String name;

    public Thread2(String name) {
        this.name = name;
    }

    @Override
    public void run() {
        System.out.println("this is "+ name + " running");
        System.out.println("实现了Runnable接口");
    }

    public static void main(String[] args) {
        Thread t1 = new Thread(new Thread2("t1"));
        t1.start();
        Thread t2 = new Thread(new Thread2("t2"));
        t2.start();
    }
}

可以继承其他类,还可以添加参数区分

  1. 实现Callable接口的call方法:
//Thread3.java
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class Thread3 implements Callable<String> {
    @Override
    public String call(){
        System.out.println("使用FutureTask方式,可以有返回值");
        return "done";
    }

    public static void main(String[] args) throws InterruptedException {
        FutureTask<String> ft = new FutureTask<String>(new Thread3());
        Thread t = new Thread(ft);
        t.start();
        try {
            String result = ft.get();
            System.out.println(result);
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}

具有返回值,可以使用get方法获得返回值.也可以继承其他类.

当调用Threadstart方法,线程只是进入了就绪状态,只有当cpu资源得到满足时,才会真正开始运行.run方法结束后,线程就处于终止状态.

wait与notify

waitnotify都是Object类中的方法.

wait

只有获得了变量的监视锁,才能调用该变量的wait方法,否则会抛出异常:

public class WaitExample {
    private int a;

    void incr() {
        a++;
    }

    int getA() {
        return a;
    }
    public static void main(String[] args) {
        WaitExample waitExample = new WaitExample();
        try {
            // wrong
            waitExample.wait();
            for (int i = 0; i < 20000; i++) {
                Thread t = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        waitExample.incr();
                    }
                });
                t.start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println(waitExample.getA());

    }
}

运行结果:

java.lang.IllegalMonitorStateException
    at java.lang.Object.wait(Native Method)
    at java.lang.Object.wait(Object.java:502)
    at com.may.learning.WaitExample.main(WaitExample.java:17)
0

获得监视锁可以通过synchronized关键字:
比如在方法上加上关键字:

    synchronized void incr() {
        a++;
    }

或者,在调用时对该类加上关键字:

synchronized (waitExample) {
...
}

当调用wait时,只会释放当前变量的锁:

    public static void main(String[] args) throws InterruptedException{
        WaitExample waitExample = new WaitExample();
        WaitExample anotherWaitExample = new WaitExample();
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (waitExample) {
                    System.out.println("t: get waitExample lock success!");
                    System.out.println("t: try get anotherWaitExample lock");
                    try {
                        synchronized (anotherWaitExample) {
                            System.out.println("t: get anotherWaitExample success!");
                            System.out.println("t: release waitExample lock");
                            // t只释放了waitExample的锁
                            waitExample.wait();

                        }
                    } catch (InterruptedException e) {
                        System.out.println("被中断");
                    }
                }

            }
        });
        t.start();
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (waitExample) {
                    System.out.println("t1: get waitExample lock success!");
                    System.out.println("t1: try get anotherWaitExample lock");
                    try {
                        // 由于t未释放锁,因此t1获取不到anotherWaitExample的锁
                        synchronized (anotherWaitExample) {
                            System.out.println("t1: get anotherWaitExample success!");
                            System.out.println("t1: release waitExample lock");
                            waitExample.wait();

                        }
                    } catch (InterruptedException e) {
                        System.out.println("被中断");
                    }
                }

            }
        });
        t1.start();
        Thread.sleep(1000);
    }

运行结果:

t: get waitExample lock success!
t: try get anotherWaitExample lock
t: get anotherWaitExample success!
t: release waitExample lock
t1: get waitExample lock success!
t1: try get anotherWaitExample lock

如果需要指定时间,可以使用wait(long timeout)或者wait(long timeout, int nanos).
wait挂起时,被中断时会抛出异常:

public class WaitExample {

    private int a;

    void incr() {
        a++;
    }

    int getA() {
        return a;
    }

    public static void main(String[] args) throws InterruptedException{
        WaitExample waitExample = new WaitExample();
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (waitExample) {
                    waitExample.incr();
                    try {
                        waitExample.wait();
                    } catch (InterruptedException e) {
                        System.out.println("被中断");
                    }
                }

            }
        });
        t.start();
        Thread.sleep(1000);
        t.interrupt();
        System.out.println(waitExample.getA());
    }
}

运行结果:

1
被中断

notify

notify会唤醒被wait阻塞挂起的线程.与wait类似,需要获得了变量的监视锁后才能对其进行进行notify操作.如果有多个线程都在等待唤醒,那么会随机唤醒某一个线程.而notifyAll会唤醒所有阻塞等待的线程.
类似wait方法,notify也需要先获得对象的监视锁(但是notify不会释放锁)。

    public static void main(String[] args) throws InterruptedException {
        NotifyExample notifyExample = new NotifyExample();
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    synchronized (notifyExample) {
                        System.out.println("t1 挂起");
                        notifyExample.wait();
                        System.out.println("t1 被唤醒了");
                    }
                } catch (InterruptedException e) {
                    System.out.println("被中断了");
                }
            }
        });
        t1.start();
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    synchronized (notifyExample) {
                        System.out.println("t2 挂起");
                        notifyExample.wait();
                        System.out.println("t2 被唤醒了");
                    }
                } catch (InterruptedException e) {
                    System.out.println("被中断了");
                }
            }
        });
        t2.start();
        Thread.sleep(1000);
        synchronized (notifyExample) {
            notifyExample.notify();
        }
    }

运行结果:

t1 挂起
t2 挂起
t1 被唤醒了

如果将notifyExample.notify()换成notifyExample.notifyAll(),那么t1t2都能被唤醒:

t1 挂起
t2 挂起
t2 被唤醒了
t1 被唤醒了

生产者消费者

利用waitnotify写一个简单的生产者消费者:

import java.util.LinkedList;
import java.util.Queue;

public class ProducerConsumer {

    public static void main(String[] args) throws InterruptedException {
        Queue<Integer> queue = new LinkedList<>();
        Thread producer = new Thread(new Runnable() {
            @Override
            public void run() {
                int i=0;
                synchronized (queue) {
                    while (true){
                        try {
                            if (!queue.isEmpty()) {
                                queue.wait();
                            }else{
                                queue.add(++i);
                                System.out.println("生产了"+i);
                                queue.notify();
                            }
                        } catch (InterruptedException e) {
                            System.out.println("被中断了");
                            return;
                        }
                    }
                }
            }
        });
        Thread consumer = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (queue) {
                    while (true){
                        try{
                            if (queue.isEmpty()) {
                                queue.wait();
                            }else{
                                int i = queue.poll();
                                System.out.println("消费了"+i);
                                queue.notify();
                            }
                        }catch (InterruptedException e){
                            System.out.println("被中断了");
                            return;
                        }
                    }
                }
            }
        });
        producer.start();
        consumer.start();
        Thread.sleep(10000);
        producer.interrupt();
        consumer.interrupt();
    }
}

运行结果:

...
生产了782421
消费了782421
生产了782422
消费了782422
生产了782423
消费了782423
生产了782424
被中断了
被中断了

join

waitnotify属于Ojbect的方法,而joinThread的方法.
调用某一线程的join方法,可以使当前线程(下例中的main线程)阻塞等待该线程完成:

public class JoinTest {

    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                    System.out.println("t 结束了!");
                } catch (InterruptedException e) {
                    System.out.println("被中断了");
                }
            }
        });
        t.start();
        t.join();
        System.out.println("main 结束了!");
    }
}

运行结果:

t 结束了!
main 结束了!

sleep

sleepwait 一样可以挂起当前线程,被中断时也会抛出异常.但不同的是它是属于Thread的方法,并且它不会释放对象的监视锁.指定睡眠时间到达后,会进入就绪状态,等待cpu的调度.

public class SleepTest {
    public static void main(String[] args) throws InterruptedException {
        SleepTest sleepTest = new SleepTest();
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (sleepTest){
                    try {
                        System.out.println("t1 获取到锁");
                        Thread.sleep(60000);
                    } catch (InterruptedException e) {
                        System.out.println("被中断了!");
                    }
                }
            }
        });
        t1.start();
        Thread.sleep(1000);
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("t2 等待锁");
                synchronized (sleepTest) {
                    System.out.println("t2 获取到锁了");
                }
            }
        });
        t2.start();
        Thread.sleep(2000);
        t1.interrupt();
    }
}

运行结果:

t1 获取到锁
t2 等待锁
被中断了!
t2 获取到锁了

yield

线程会主动让出自己的cpu时间,并不会被挂起,只是进入了就绪状态.但是下一次仍然可能被调度到.

中断

前面已经使用了interrupt很多次,需要注意与isInterrupted以及interrupted进行区分.
isInterrupted: 判断当前线程是否被中断;
interrupted: 判断当前线程是否被中断,并且复位(清除中断标志);

使用interrupted判断中断并且复位:

public class InterruptTest {

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                while (!Thread.interrupted()) {

                }
                System.out.println("t1 is Interrupted: "+Thread.currentThread().isInterrupted());
            }
        });
        t1.start();
        t1.interrupt();
        t1.join();
        System.out.println("done");
    }
}

运行结果:

t1 is Interrupted: false
done

需要注意的是调用线程的interrupt方法,只是为该线程设置中断位.当线程在运行时,会立即往下执行.而当被wait,join或者sleep方法阻塞挂起时,才会抛出InterruptedException异常,此时中断位会被恢复,如下面这个例子:

public class InterruptTest throws InterruptedException{

    public static void main(String[] args){
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("t1 running");
                while (true) {
                }
            }
        });
        t1.start();
        t1.interrupt();
        System.out.println("main thread isInterrupted: " + Thread.interrupted());
        System.out.println("t1 isInterrupted: " + t1.isInterrupted());
        boolean isInterrupted = Thread.interrupted();
        System.out.println("isInterrupted: " + isInterrupted);
        System.out.println("main thread isInterrupted: " + Thread.interrupted());
        System.out.println("t1 isInterrupted: " + t1.isInterrupted());
        t1.join();
        System.out.println("done");
    }
}

输出结果:

main thread isInterrupted: false
t1 isInterrupted: true
isInterrupted: false
main thread isInterrupted: false
t1 running
t1 isInterrupted: true

因为t1并没有被挂起,所以即使中断位为true,也仍然在继续运行,不会输出"done".而interrupted针对是当前线程,也就是主线程,所以中断标志位一直是false.
如果在阻塞情况下,中断位会被马上复位,对上面的例子稍加修改:

public class InterruptTest {

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    while (!Thread.currentThread().isInterrupted()) {
                        System.out.println("t1: running");
                        Thread.sleep(1000);
                    }
                }catch (Exception e){
                    System.out.println("t1 被中断");
                    System.out.println("thread t1 isInterrupted : "+Thread.currentThread().isInterrupted());
                }
            }
        });
        t1.start();
        Thread.sleep(1000);
        t1.interrupt();
        System.out.println("main thread isInterrupted: " + Thread.interrupted());
        System.out.println("t1 isInterrupted: " + t1.isInterrupted());
        t1.join();
        System.out.println("done");
    }
}

运行结果:

t1: running
t1 被中断
thread t1 isInterrupted : false
main thread isInterrupted: false
t1 isInterrupted: false
done

主线程中的isInterrupted仍然是false,但是打印出的t1isInterrupted由于处在阻塞状态被中断,中断位又被复位成了false.

上下文切换与死锁

当出现:

  • CPU时间用尽,线程进入就绪状态时
  • 被其他线程中断时

会出现上下文的切换.

避免死锁的出现,可以采用不同线程都按照相同的顺序去请求资源,保证资源获取的有序一致性.

守护线程与用户线程

守护线程的存在不影响JVM的退出,只要最后一个用户线程没有退出,正常情况下JVM也不会退出.
JVM没有退出:

public class DaemonTest {

    public static void main(String[] args) {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {

                }
            }
        });
//        t.setDaemon(true);
        t.start();
        System.out.println("main exit");
    }
}

运行结果:

main exit

t利用setDeamon设置为守护线程的注释打开,运行结果:

main exit

Process finished with exit code 0

原理是,main运行后,JVM会自动启动一个叫做DestoryJavaVM的线程,它会等待所有用户线程结束后终止JVM进程.

ThreadLocal

如果创建了一个ThreadLocal变量,每个访问这个变量的线程都会获得一个副本.

public class ThreadLocalTest {
    static ThreadLocal<Integer> val = new ThreadLocal<>();

    static void print(String string) {
        System.out.println(string + ":" + val.get());
    }
    public static void main(String[] args) {
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                val.set(1);
                for (int i = 0; i < 50; i++) {
                    int v = val.get();
                    v++;
                    val.set(v);
                }
                print("thread1");
                val.remove();
                print("after remove thread1");
            }
        });
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                val.set(1);
                for (int i = 0; i < 50; i++) {
                    int v = val.get();
                    v += 2;
                    val.set(v);
                }
                print("thread2");
                val.remove();
                print("after remove thread2");
            }
        });
        t1.start();
        t2.start();
        System.out.println("done");
    }
}

运行结果:

thread1:51
after remove thread1:null
done
thread2:101
after remove thread2:null

ThreadLocal的原理:

  1. Thread中有一个threadLocals变量,它的类型是ThreadLocal.ThreadLocalMap,实际上是一个hashMap.
  2. 当使用set方法赋值时:
// ThreadLocal.java
    public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }

getMap方法获得的是threadLocals,如果不为空,将当前threadLocal变量作为key,设置的值作为value放入进行存储,而如果为空,则利用createMap进行初始化.

// ThreadLocal.java
    void createMap(Thread t, T firstValue) {
        t.threadLocals = new ThreadLocalMap(this, firstValue);
    }

需要注意的是createMap中传入的是当前线程,因为需要为其设置threadLocals变量的值.而threadLocals中的key实际上是ThreadLocal变量,也就是可以理解为:thread1.threadLocals -> {ThreadLocal@xxx:1, ThreadLocal@yyy:"hello"}

但是ThreadLocal不支持继承,如果需要继承父线程的值,需要使用InheritableThreadLocal:

public class InheritThreadLocalTest {
    static InheritableThreadLocal<String> inheritableThreadLocal = new InheritableThreadLocal<>();

    static void print(String str) {
        System.out.println(str + ":" + inheritableThreadLocal.get());
    }

    public static void main(String[] args) {
        inheritableThreadLocal.set("hello");
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                String initVal = inheritableThreadLocal.get();
                if (initVal != null) {
                    inheritableThreadLocal.set(initVal+" world");
                }
                print("thread 1");
            }
        });
        t.start();
        print("main");
        System.out.println("done");
    }
}

运行结果:

main:hello
done
thread 1:hello world

InheritableThreadLocalThreadLocalset方法是一样的,区别在于createMap,它将变量写入了inheritableThreadLocals里:

    void createMap(Thread t, T firstValue) {
        t.inheritableThreadLocals = new ThreadLocalMap(this, firstValue);
    }

在初始化线程的时候,init方法会设置inheritableThreadLocals:

    private void init(ThreadGroup g, Runnable target, String name,
                      long stackSize, AccessControlContext acc,
                      boolean inheritThreadLocals){
...
        if (inheritThreadLocals && parent.inheritableThreadLocals != null)
            this.inheritableThreadLocals =
                ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
...
}

它会将父线程的inheritableThreadLocals都复制到自己的inheritableThreadLocals中.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,921评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,635评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,393评论 0 338
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,836评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,833评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,685评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,043评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,694评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 42,671评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,670评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,779评论 1 332
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,424评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,027评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,984评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,214评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,108评论 2 351
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,517评论 2 343

推荐阅读更多精彩内容