一、什么是多线程之间通讯
多线程之间通讯,其实就是多个线程在操作同一个资源,但是操作的动作不同
二、多线程之间通讯案例
需求:第一个线程写入用户,另一个线程读取用户,实现读一个,写一个操作
class Res{
public String userSex;
public String userName;
}
/**
* 写入线程
*
*/
class InThread extends Thread{
private Res res;
public InThread(Res res) {
this.res=res;
}
@Override
public void run() {
int count=0;
while (true) {
if(count==0) {
res.userName="小明";
res.userSex="男";
}else {
res.userName="小红";
res.userSex="女";
}
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("name:"+res.userName+"sex:"+res.userSex);
}
}
}
public class Test001 {
public static void main(String[] args) {
Res res = new Res();
InThread inThread = new InThread(res);
inThread.start();
OutThread outThread = new OutThread(res);
outThread.start();
}
}
运行代码
数据发送错乱,造成线程安全问题
解决方法:再输入线程和输出线程都加上synchronized
class Res {
public String userSex;
public String userName;
}
/**
* 写入线程
*
*/
class InThread extends Thread {
private Res res;
public InThread(Res res) {
this.res = res;
}
@Override
public void run() {
int count = 0;
while (true) {
synchronized (res) {
if (count == 0) {
res.userName = "小明";
res.userSex = "男";
} else {
res.userName = "小红";
res.userSex = "女";
}
count = (count + 1) % 2;
}
}
}
}
/**
* 读取线程
*
*
*/
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("name:" + res.userName + "sex:" + res.userSex);
}
}
}
}
public class Test001 {
public static void main(String[] args) {
Res res = new Res();
InThread inThread = new InThread(res);
inThread.start();
OutThread outThread = new OutThread(res);
outThread.start();
}
}
运行代码
不会出现数据错乱问题,但还满足不了读一个,写一个的操作
2.1 wait、notify方法
- 因为涉及到对象锁,他们必须都放在synchronized中来使用。wait、Notify一定要在synchronized里面进行使用
- wait必须暂停当前正在执行的线程,并释放资源锁,让其他线程可以有机会运行
- notify/notiyall:唤醒因锁池中的线程,使之运行
注意:一定要在线程同步中使用,并且时同一个锁的资源
class Res {
public String userSex;
public String userName;
//线程通讯标识
public boolean flag=false;
}
/**
* 写入线程
*
*/
class InThread extends Thread {
private Res res;
public InThread(Res res) {
this.res = res;
}
@Override
public void run() {
int count = 0;
while (true) {
synchronized (res) {
if(res.flag) {
try {
res.wait();//线程等待,并释放锁
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (count == 0) {
res.userName = "小明";
res.userSex = "男";
} else {
res.userName = "小红";
res.userSex = "女";
}
count = (count + 1) % 2;
res.flag=true;
res.notify();//唤醒其他线程
}
}
}
}
/**
* 读取线程
*
*
*/
class OutThread extends Thread {
private Res res;
public OutThread(Res res) {
this.res = res;
}
@Override
public void run() {
while (true) {
synchronized (res) {
if(!res.flag) {
try {
res.wait();//线程等待,并释放锁
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("name:" + res.userName + "sex:" + res.userSex);
res.flag=false;
res.notify();//唤醒其他线程
}
}
}
}
public class Test001 {
public static void main(String[] args) {
Res res = new Res();
InThread inThread = new InThread(res);
inThread.start();
OutThread outThread = new OutThread(res);
outThread.start();
}
}
2.2wait与sleep区别
对于sleep()方法,我们首先要知道该方法是属于Thread类中的。而wait()方法,则是属于Object类中的。
sleep()方法导致了程序暂停执行指定的时间。让出了cpu给其他线程,但是他的监控状态依然是保持者,当指定的时间到了又会自动恢复运行状态。在调用sleep()方法的过程中,线程不会释放对象锁。而当调用wait()方法的时候,线程会放弃对象锁,进入等待此对象的等待锁池,只有针对此对象调用notify()方法后该线程才进入对象锁定池准备获取对象锁进入运行状态
三、Lock锁
在jdk1.5之后,并发包中新增了Lock接口(以及相关实现类)用来实现锁功能,Lock接口提供了与synchronized关键字类似的同步功能,但需要在使用时手动获取锁和释放锁
3.1Lock与synchronized关键字的区别
Lock接口可以尝试非阻塞地获取锁当前线程尝试获取锁。如果这一时刻锁没有被其他线程获取到,则成功获取并持有锁
Lock接口能被中断地获取锁与synchronized不同,获取到锁的线程能够响应中断,当获取到的锁的线程被中断时,中断异常将会被抛出,同时锁会被释放
Lock接口在指定的截止时间之前获取锁,如果截止时间到了依旧无法获取锁,则返回
3.2Condition用法
Condition的功能类似于在传统的线程技术中的,Object.wait()和Object.notify()的功能
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class Res1 {
public String userName;
public String sex;
public boolean flag = false;
Lock lock = new ReentrantLock();
}
/**
*
* 写入线程
*
*/
class InputThread extends Thread {
private Res1 res;
private Condition newCondition;
public InputThread(Res1 res, Condition newCondition) {
this.res = res;
this.newCondition = newCondition;
}
@Override
public void run() {
int count=0;
while (true) {
try {
res.lock.lock();
if (res.flag) {
newCondition.await();
}
if(count==0) {
res.userName="小明";
res.sex="男";
}else {
res.userName="小红";
res.sex="女";
}
count=(count+1)%2;
res.flag=true;
newCondition.signal();
} catch (Exception e) {
// TODO: handle exception
} finally {
res.lock.unlock();
}
}
}
}
/**
*
* 读取线程
*
*/
class OutputThread extends Thread{
private Res1 res;
private Condition newCondition;
public OutputThread(Res1 res, Condition newCondition) {
this.res = res;
this.newCondition = newCondition;
}
@Override
public void run() {
while (true) {
try {
res.lock.lock();
if(!res.flag) {
newCondition.await();
}
System.out.println("name:"+res.userName+"sex:"+res.sex);
res.flag=false;
newCondition.signal();
}catch (Exception e) {
// TODO: handle exception
}finally {
res.lock.unlock();
}
}
}
}
public class Test002 {
public static void main(String[] args) {
Res1 res1 = new Res1();
Condition newCondition = res1.lock.newCondition();
InputThread inputThread = new InputThread(res1, newCondition);
inputThread.start();
OutputThread outThread = new OutputThread(res1, newCondition);
outThread.start();
}
}