线程间通信
举例:
package 多线程day12;
/**
* 线程通信
* @author long
*
*/
// 资源
class Res{
public String name;
public int age;
}
// 输入线程
class Input implements Runnable{
private Res res;
public Input(Res res){
this.res = res;
}
@Override
public void run() {
// TODO Auto-generated method stub
int x = 0;
while(true){
if(x==0){
add("alex",20);
}else{
add("张三",60);
}
x= (x+1)%2;
}
}
private void add(String name,int age){
res.name = name;
res.age = age;
}
}
// 输出线程
class Output implements Runnable{
private Res res;
public Output(Res res){
this.res = res;
}
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
get();
}
}
public void get(){
System.out.println(res.name+"--->"+res.age);
}
}
public class ThreadTake {
public static void main(String[] args) {
Res res = new Res();
Thread t1 = new Thread(new Input(res));
Thread t2 = new Thread(new Output(res));
t1.start();
t2.start();
}
}
/*
张三--->20
alex--->20
alex--->20
alex--->60
张三--->60
*
* 出现这种情况的原因:
* input 线程 在操作 res对象时,只对name进行了赋值,还未给age赋值,
* 这时output 线程进来取走了name和age,所以就会出现错乱。
* */
出现这种情况的原因:
input 线程 在操作 res对象时,只对name进行了赋值,还未给age赋值,
这时output 线程进来取走了name和age,所以就会出现错乱
问题解决
package 多线程day12;
/**
* 线程通信
* @author long
*
*/
class Res{
public String name;
public int age;
}
class Input implements Runnable{
private Res res;
public Input(Res res){
this.res = res;
}
@Override
public void run() {
// TODO Auto-generated method stub
int x = 0;
while(true){
if(x==0){
add("alex",20);
}else{
add("张三",60);
}
x= (x+1)%2;
}
}
private void add(String name,int age){
// 加上同步代码块 // 锁必须是同一个对象
synchronized(res){
res.name = name;
res.age = age;
}
}
}
class Output implements Runnable{
private Res res;
public Output(Res res){
this.res = res;
}
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
get();
}
}
public void get(){
// 加上同步代码块 // 锁必须是同一个对象
synchronized(res){
System.out.println(res.name+"--->"+res.age);
}
}
}
public class ThreadTake {
public static void main(String[] args) {
Res res = new Res();
Thread t1 = new Thread(new Input(res));
Thread t2 = new Thread(new Output(res));
t1.start();
t2.start();
}
}
新问题:input 线程拿到锁会一直赋值,覆盖之前的内容,output 线程拿到锁会一直输出。
/**
* 线程通信
* @author long
*
*/
class Res{
public String name;
public int age;
public boolean flag = false;
}
class Input implements Runnable{
private Res res;
public Input(Res res){
this.res = res;
}
@Override
public void run() {
// TODO Auto-generated method stub
int x = 0;
while(true){
// 加上同步代码块 // 锁必须是同一个对象
synchronized(res){
if(res.flag)
try {res.wait();} catch (InterruptedException e) {e.printStackTrace();} // 等待
if(x==0){
res.name = "alex";
res.age = 20;
}else{
res.name = "张三";
res.age = 60;
}
x= (x+1)%2;
res.flag = true;
res.notify(); // 唤醒同一个锁下的另一个线程
}
}
}
}
class Output implements Runnable{
private Res res;
public Output(Res res){
this.res = res;
}
@Override
public void run() {
while(true){
// 加上同步代码块 // 锁必须是同一个对象
synchronized(res){
if(!res.flag)
try {res.wait();} catch (InterruptedException e) {e.printStackTrace();} // 等待
System.out.println(res.name+"--->"+res.age);
res.flag = false;
res.notify(); // 唤醒同一个锁下的另一个线程
}
}
}
}
public class ThreadTake {
public static void main(String[] args) {
Res res = new Res();
Thread t1 = new Thread(new Input(res));
Thread t2 = new Thread(new Output(res));
t1.start();
t2.start();
}
}
/*
wait: // 等待,释放cup执行权,释放锁
notify(); // 唤醒同一个锁下的一个线程(多个线程随机分配)获取cup执行权,获取锁
notifyAll(); // 唤醒同一个锁下的所有线程,竞争锁,
都使用在同步中,因为要对持有监视器(锁)的线程操作。
所以要使用在同步中,因为只有同步才具有锁。
为什么这些操作线程的方法要定义Object类中呢?
等待和唤醒必须是同一个锁。
而锁可以是任意对象,所以可以被任意对象调用的方法定义Object类中。
*/
wait: // 等待,释放cup执行权,释放锁
notify(); // 唤醒同一个锁下的一个线程(多个线程随机分配)获取cup执行权,获取锁
notifyAll(); // 唤醒同一个锁下的所有线程,竞争锁,
都使用在同步中,因为要对持有监视器(锁)的线程操作。所以要使用在同步中,因为只有同步才具有锁。
为什么这些操作线程的方法要定义Object类中呢?
等待和唤醒必须是同一个锁,而锁可以是任意对象,所以可以被任意对象调用的方法定义Object类中。
代码简化
/**
* 线程通信
* @author long
*
*/
class Res{
private String name;
private int age;
private boolean flag = false;
public synchronized void setNameAge(String name,int age) {
if(flag)
try {this.wait();} catch (InterruptedException e) {e.printStackTrace();} // 等待
this.name = name;
this.age = age;
flag = true;
this.notify();
}
public synchronized void out() {
if(!flag)
try {this.wait();} catch (InterruptedException e) {e.printStackTrace();} // 等待
System.out.println(this.name+"-->"+this.age);
flag = false;
this.notify();
}
}
class Input implements Runnable{
private Res res;
public Input(Res res){
this.res = res;
}
@Override
public void run() {
// TODO Auto-generated method stub
int x = 0;
while(true){
if(x==0) {
res.setNameAge("axle", 20);
}else {
res.setNameAge("张三", 60);
}
x=(x+1)%2;
}
}
}
class Output implements Runnable{
private Res res;
public Output(Res res){
this.res = res;
}
@Override
public void run() {
while(true){
res.out();
}
}
}
public class ThreadTake2 {
public static void main(String[] args) {
Res res = new Res();
Thread t1 = new Thread(new Input(res));
Thread t2 = new Thread(new Output(res));
t1.start();
t2.start();
}
}
生产者消费者模型
上面的简化代码是一个生产者和一个消费者,若有多个生产者与多个消费者,就会出现如下问题:
// 资源
class Resource{
private String name;
private int count = 0;
private boolean flag = false;
public synchronized void set(String name) {
if(flag) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this.name = name +"---"+count++;
System.out.println("生产:"+this.name);
flag = true;
this.notify();
}
public synchronized void out() {
if(!flag) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("消费..."+name);
flag = false;
this.notify();
}
}
//生产者
class Producer implements Runnable{
private Resource res;
public Producer(Resource res) {
// TODO Auto-generated constructor stub
this.res = res;
}
@Override
public void run() {
while(true) {
res.set("包子");
}
}
}
//消费者
class Consumer implements Runnable{
private Resource res;
public Consumer(Resource res) {
// TODO Auto-generated constructor stub
this.res = res;
}
@Override
public void run() {
while(true) {
res.out();
}
}
}
public class ProducerConsumer {
public static void main(String[] args) {
Resource res = new Resource();
Thread t1 = new Thread(new Producer(res));
Thread t2 = new Thread(new Producer(res));
Thread t3 = new Thread(new Consumer(res));
Thread t4 = new Thread(new Consumer(res));
t1.start();
t2.start();
t3.start();
t4.start();
}
}
/*
生产:包子---73316
生产:包子---73317
生产:包子---73318
消费...包子---73318
出现生产了多个包子值消费量最后一个,产生一个包子,消费了几次
产生现象的原因:
t1,t2 生产者
t3,t4 消费者
t1 生产一个包子,设置flag = true,t1再次,进来处于等待状态,
t2进来flag = true,t2处于等待状态,
t3进来消费一个包子,设置flag = false,唤醒一个线程(随机的),
t4进来flag = false,t4等待
t2被唤醒,(刚才处于等待状态,直接跳过了flag的判断),生产一个包子,随机唤醒一个线程
t1被唤醒,(直接跳过了flag的判断)生产一个包子,随机唤醒一个线程
......
*/
问题解决:
由于处于等待状态,直接跳过了flag的判断,可将if改为while。
当改成while又会出现,锁有的线程都处于等待状态。
出现原因:
notify每次随机唤醒一个线程,(当t1处于等待状态;执行t2,t2处于等待;执行t3,唤醒了t1,t3处于等待状态;执行t4,t4处于等待状态;执行唤醒的t1,唤醒了t2,t1处于等待状态;执行t2,t2处于等待状态;至此所有的线程都处于等待状态。)
解决办法:
将notify 改为 notifyAll();
// 资源
class Resource{
private String name;
private int count = 0;
private boolean flag = false;
public synchronized void set(String name) {
while(flag) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this.name = name +"---"+count++;
System.out.println("生产:"+this.name);
flag = true;
this.notifyAll();
}
public synchronized void out() {
while(!flag) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("消费..."+name);
flag = false;
this.notifyAll();
}
}
//生产者
class Producer implements Runnable{
private Resource res;
public Producer(Resource res) {
// TODO Auto-generated constructor stub
this.res = res;
}
@Override
public void run() {
while(true) {
res.set("包子");
}
}
}
//消费者
class Consumer implements Runnable{
private Resource res;
public Consumer(Resource res) {
// TODO Auto-generated constructor stub
this.res = res;
}
@Override
public void run() {
while(true) {
res.out();
}
}
}
public class ProducerConsumer {
public static void main(String[] args) {
Resource res = new Resource();
Thread t1 = new Thread(new Producer(res));
Thread t2 = new Thread(new Producer(res));
Thread t3 = new Thread(new Consumer(res));
Thread t4 = new Thread(new Consumer(res));
t1.start();
t2.start();
t3.start();
t4.start();
}
}
生产者消费者升级版
JDK1.5 中提供了多线程升级解决方案。
将同步Synchronized替换成现实Lock操作,可以支持多个相关的 Condition 对象。
将Object中的wait,notify notifyAll,替换成Condition对象。该对象可以通过Lock锁 进行获取。
可以实现了本方只唤醒对方操作。
Lock:替代了Synchronized
lock
unlock
newCondition()
Condition:替代了Object wait notify notifyAll
await();
signal();
signalAll();
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/** 生产者消费者升级
* 1.5新特性
*
*/
// 资源
class Resource{
private String name;
private int count = 0;
private boolean flag = false;
private ReentrantLock lock = new ReentrantLock(); // 创建一个锁
// condition 相当于将锁中的线程对象进行了分组,只能操作组中的线程对象。
private Condition condition_pro = lock.newCondition(); // Condition 替代了 Object 监视器方法的使用。
private Condition condition_con = lock.newCondition();
public void set(String name) {
lock.lock(); // 加锁
try {
while(flag) {
try {
condition_pro.await(); // 生产者等待
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this.name = name +"---"+count++;
System.out.println("生产:"+this.name);
flag = true;
condition_con.signal(); // 唤醒一个消费者
}finally {
lock.unlock(); // 解锁,最后一定要解锁
}
}
public synchronized void out() {
lock.lock(); //加锁
try {
while(!flag) {
try {
condition_con.await(); // 消费者等待
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("消费..."+name);
flag = false;
condition_pro.signal(); //唤醒一个生产者
}
finally {
lock.unlock(); //解锁
}
}
}
//生产者
class Producer implements Runnable{
private Resource res;
public Producer(Resource res) {
// TODO Auto-generated constructor stub
this.res = res;
}
@Override
public void run() {
while(true) {
res.set("包子");
}
}
}
//消费者
class Consumer implements Runnable{
private Resource res;
public Consumer(Resource res) {
// TODO Auto-generated constructor stub
this.res = res;
}
@Override
public void run() {
while(true) {
res.out();
}
}
}
public class ProducerConsumer2 {
public static void main(String[] args) {
Resource res = new Resource();
Thread t1 = new Thread(new Producer(res));
Thread t2 = new Thread(new Producer(res));
Thread t3 = new Thread(new Consumer(res));
Thread t4 = new Thread(new Consumer(res));
t1.start();
t2.start();
t3.start();
t4.start();
}
}
/*
*
Lock 实现提供了比使用 synchronized 方法和语句可获得的更广泛的锁定操作。
此实现允许更灵活的结构,可以具有差别很大的属性,可以支持多个相关的 Condition 对象
Condition 将 Object 监视器方法(wait、notify 和 notifyAll)分解成截然不同的对象,
以便通过将这些对象与任意 Lock 实现组合使用,为每个对象提供多个等待 set(wait-set)。
其中,Lock 替代了 synchronized 方法和语句的使用,Condition 替代了 Object 监视器方法的使用。
*/
/*
JDK1.5 中提供了多线程升级解决方案。
将同步Synchronized替换成现实Lock操作。
将Object中的wait,notify notifyAll,替换成Condition对象。
该对象可以通过Lock锁 进行获取。
该示例中,实现了本方只唤醒对方操作。
Lock:替代了Synchronized
lock
unlock
newCondition()
Condition:替代了Object wait notify notifyAll
await();
signal();
signalAll();
*/