3.多线程之间通讯

什么是多线程之间通讯?

多线程之间通讯,其实就是多个线程在操作同一个资源,但是操作的动作不同。

多线程之间通讯需求

需求:第一个线程写入(input)用户,另一个线程取读取(out)用户。实现读一个,写一个操作。

代码实现基本实现

共享资源源实体类
class Res {
    public String userName;
    public String sex;
}
输入线程资源
class IntThrad extends Thread {
    private Res res;

    public IntThrad(Res res) {
        this.res = res;
    }

    @Override
    public void run() {
        int count = 0;
        while (true) {
            if (count == 0) {
                res.userName = "zhangsan";
                res.sex= "男";
            } else {
                res.userName = "lisi";
                res.sex= "女";
            }
            count = (count + 1) % 2;
        }
    }
}
输出线程
class OutThread extends Thread {
    private Res res;

    public OutThread(Res res) {
        this.res = res;
    }

    @Override
    public void run() {
        while (true) {
            System.out.println(res.userName + "--" + res.sex);
        }
    }
}
运行代码
Res res = new Res();
IntThrad intThrad = new IntThrad(res);
OutThread outThread = new OutThread(res);
intThrad.start();
outThread.start();
运行结果

注意:数据发生错乱,造成线程安全问题

解决线程安全问题

输入线程加上synchronized
class IntThrad extends Thread {
    private Res res;

    public IntThrad(Res res) {
        this.res = res;
    }

    @Override
    public void run() {
        int count = 0;
        while (true) {
            synchronized (res) {
                if (count == 0) {
                    res.userName = "zhangsan";
                    res.sex = "男";
                } else {
                    res.userName = "lisi";
                    res.sex = "女";
                }
                count = (count + 1) % 2;
            }
        }
    }
}
输出线程加上synchronized
class OutThread extends Thread {
    private Res res;

    public OutThread(Res res) {
        this.res = res;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (res) {
                System.out.println(res.userName + "," + res.sex);
            }
        }
    }
}
运行结果

wait()、notify、notifyAll()方法

  • wait()、notify()、notifyAll()是三个定义在Object类里的方法,可以用来控制线程的状态。这三个方法最终调用的都是jvm级的native方法。随着jvm运行平台的不同可能有些许差异。
  • 如果对象调用了wait方法就会使持有该对象的线程把该对象的控制权交出去,然后处于等待状态。
  • 如果对象调用了notify方法就会通知某个正在等待这个对象的控制权的线程可以继续运行。
  • 如果对象调用了notifyAll方法就会通知所有等待这个对象控制权的线程继续运行。

注意:一定要在线程同步中使用,并且是同一个锁的资源

输入线程加上wait()、notify
class IntThrad extends Thread {
    private Res_3 res;

    public IntThrad_3(Res_3 res) {
        this.res = res;
    }

    @Override
    public void run() {
        int count = 0;
        while (true) {
            synchronized (res) {
                if (res.flag) {
                    try {
                        // 当前线程变为等待,但是可以释放锁
                        res.wait();
                    } catch (Exception e) {
                    }
                }
                if (count == 0) {
                    res.userName = "zhangsan";
                    res.sex = "男";
                } else {
                    res.userName = "lisi";
                    res.sex = "女";
                }
                count = (count + 1) % 2;
                res.flag = true;
                // 唤醒当前线程
                res.notify();
            }
        }
    }
}
输出线程加上wait()、notify
class OutThread extends Thread {
    private Res_3 res;

    public OutThread_3(Res_3 res) {
        this.res = res;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (res) {
                if (!res.flag) {
                    try {
                        res.wait();
                    } catch (Exception e) {
                        // TODO: handle exception
                    }
                }
                System.out.println(res.userName + "," + res.sex);
                res.flag = false;
                res.notify();
            }
        }
    }
}
运行结果

wait与sleep区别?

  • 对于sleep()方法,我们首先要知道该方法是属于Thread类中的。而wait()方法,则是属于Object类中的。
  • sleep()方法导致了程序暂停执行指定的时间,让出cpu该其他线程,但是他的监控状态依然保持者,当指定的时间到了又会自动恢复运行状态。在调用sleep()方法的过程中,线程不会释放对象锁。
  • 而当调用wait()方法的时候,线程会放弃对象锁,进入等待此对象的等待锁定池,只有针对此对象调用notify()方法后本线程才进入对象锁定池准备,获取对象锁进入运行状态。

JDK1.5 Lock

在 jdk1.5 之后,并发包中新增了 Lock 接口(以及相关实现类)用来实现锁功能,Lock 接口提供了与 synchronized 关键字类似的同步功能,但需要在使用时手动获取锁和释放锁。

Lock写法

Lock lock = new ReentrantLock();
lock.lock();
try {
    //可能会出现线程安全的操作
} 
finally {
    //一定在finally中释放锁
    //也不能把获取锁在try中进行,因为有可能在获取锁的时候抛出异常
    lock.unlock();
}

Lock 接口与 synchronized 关键字的区别

  • Lock 接口可以尝试非阻塞地获取锁当前线程尝试获取锁。如果这一时刻锁没有被其他线程获取到,则成功获取并持有锁。
  • Lock 接口能被中断地获取锁与 synchronized 不同,获取到锁的线程能够响应中断,当获取到的锁的线程被中断时,中断异常将会被抛出,同时锁会被释放。
  • Lock 接口在指定的截止时间之前获取锁,如果截止时间到了依旧无法获取锁,则返回。

Condition用法

Condition的功能类似于在传统的线程技术中的Object.wait()和Object.notify()的功能。

Condition写法

Condition condition = lock.newCondition();
res.condition.await(); // 类似wait
res.Condition.Signal() // 类似notify

案例改进

将synchronized换为ReentrantLock
wait和notify由Condition的await和signal

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 线程安全4_解决线程安全问题
 * 将synchronized换为ReentrantLock
 * wait和notify由Condition的await和signal
 */

class Res_4 {
    public String sex;
    public String userName;
    //线程通讯标识
    public boolean flag = false;
    Lock lock = new ReentrantLock();
}

class IntThrad_4 extends Thread {
    private Res_4 res;
    private Condition condition;

    public IntThrad_4(Res_4 res, Condition condition) {
        this.res = res;
        this.condition = condition;
    }

    @Override
    public void run() {
        int count = 0;
        while (true) {
            try {
                res.lock.lock();
                if (res.flag) {
                    try {
                        // 当前线程变为等待,但是可以释放锁
//                        res.wait();
                        condition.await();
                    } catch (Exception e) {
                    }
                }
                if (count == 0) {
                    res.userName = "zhangsan";
                    res.sex = "男";
                } else {
                    res.userName = "lisi";
                    res.sex = "女";
                }
                count = (count + 1) % 2;
                res.flag = true;
                // 唤醒当前线程
//                res.notify();
                condition.signal();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                res.lock.unlock();
            }
        }
    }

}

class OutThread_4 extends Thread {
    private Res_4 res;
    private Condition condition;

    public OutThread_4(Res_4 res, Condition condition) {
        this.res = res;
        this.condition = condition;
    }

    @Override
    public void run() {
        while (true) {
            try {
                res.lock.lock();
                if (!res.flag) {
                    try {
//                        res.wait();
                        condition.await();
                    } catch (Exception e) {
                    }
                }
                System.out.println(res.userName + "," + res.sex);
                res.flag = false;
//                res.notify();
                condition.signal();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                res.lock.unlock();
            }
        }
    }
}

public class Lock_Condition4 {
    public static void main(String[] args) {
        Res_4 res = new Res_4();
        Condition condition = res.lock.newCondition();
        IntThrad_4 intThrad = new IntThrad_4(res, condition);
        OutThread_4 outThread = new OutThread_4(res, condition);
        intThrad.start();
        outThread.start();
    }
}

如何停止线程?

停止线程思路

  1. 使用退出标志,使线程正常退出,也就是当run方法完成后线程终止。
  2. 使用stop方法强行终止线程(这个方法不推荐使用,因为stop和suspend、resume一样,也可能发生不可预料的结果)。
  3. 使用interrupt方法中断线程。
class StopThread implements Runnable {
    private boolean flag = true;

    @Override
    public synchronized void run() {
        while (flag) {
            try {
                wait();
            } catch (Exception e) {
                e.printStackTrace();
                stopThread();
            }
            System.out.println("thread run..");
        }
    }

    public void stopThread() {
        flag = false;
    }
}

public class StopThreadDemo {
    public static void main(String[] args) {
        StopThread stopThread1 = new StopThread();
        Thread thread1 = new Thread(stopThread1);
        Thread thread2 = new Thread(stopThread1);
        thread1.start();
        thread2.start();
        int i = 0;
        while (true) {
            System.out.println("thread main..");
            if (i == 30) {
                // stopThread1.stopThread();
                thread1.interrupt();
                thread2.interrupt();
                break;
            }
            i++;
        }
    }
}

运行结果

通过抛出异常的方式来执行停止线程的方法

ThreadLocal

什么是ThreadLocal

ThreadLocal提高一个线程的局部变量,访问某个线程拥有自己局部变量。
当使用ThreadLocal维护变量时,ThreadLocal为每个使用该变量的线程提供独立的变量副本,所以每一个线程都可以独立地改变自己的副本,而不会影响其它线程所对应的副本。

ThreadLocal的接口方法

  • void set(Object value)设置当前线程的线程局部变量的值。
  • public Object get()该方法返回当前线程所对应的线程局部变量。
  • public void remove()将当前线程局部变量的值删除,目的是为了减少内存的占用,该方法是JDK 5.0新增的方法。需要指出的是,当线程结束后,对应该线程的局部变量将自动被垃圾回收,所以显式调用该方法清除线程的局部变量并不是必须的操作,但它可以加快内存回收的速度。
  • protected Object initialValue()返回该线程局部变量的初始值,该方法是一个protected的方法,显然是为了让子类覆盖而设计的。这个方法是一个延迟调用方法,在线程第1次调用get()或set(Object)时才执行,并且仅执行1次。ThreadLocal中的缺省实现直接返回一个null。

案例:创建三个线程,每个线程生成自己独立序列号。

未使用ThreadLocal
class Res1 {
    public Integer count = 0;

    public Integer getNum() {
        return ++count;
    }
}

public class ThreadLocalDemo1 extends Thread {
    private Res1 res;

    public ThreadLocalDemo1(Res1 res) {
        this.res = res;
    }

    @Override
    public void run() {
        for (int i = 0; i < 3; i++) {
            System.out.println(Thread.currentThread().getName() + " num:" + res.getNum());
        }

    }
    public static void main(String[] args) {
        Res1 res1 = new Res1();
        Res1 res2 = new Res1();
        Res1 res3 = new Res1();
        ThreadLocalDemo1 t1 = new ThreadLocalDemo1(res1);
        ThreadLocalDemo1 t2 = new ThreadLocalDemo1(res2);
        ThreadLocalDemo1 t3 = new ThreadLocalDemo1(res3);
        t1.start();
        t2.start();
        t3.start();
    }
}

运行结果

未使用ThreadLocal前,如果想要每个线程都需为每个线程单独开一个共享资源
使用ThreadLocal
class Res2 {
    public static ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>() {
        protected Integer initialValue() {
            return 0;
        };
    };

    public Integer getNum() {
        int count = threadLocal.get() + 1;
        threadLocal.set(count);
        return count;
    }
}
public class ThreadLocalDemo2 extends Thread {
    private Res2 res;

    public ThreadLocalDemo2(Res2 res) {
        this.res = res;
    }

    @Override
    public void run() {
        for (int i = 0; i < 3; i++) {
            System.out.println(Thread.currentThread().getName() + " num:" + res.getNum());
        }

    }

    public static void main(String[] args) {
        Res2 res = new Res2();
        ThreadLocalDemo2 t1 = new ThreadLocalDemo2(res);
        ThreadLocalDemo2 t2 = new ThreadLocalDemo2(res);
        ThreadLocalDemo2 t3 = new ThreadLocalDemo2(res);
        t1.start();
        t2.start();
        t3.start();
    }
}

ThreadLocal底层实现伪代码

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