文件在E:\学习文档子目录压缩\并发技术\J2SE多线程基础 或我的网盘\我的笔记\学习文档子目录压缩\并发技术\J2SE多线程基础下
Thread3.java
package com.xiangshuai.thread;
class Res{
private String name;
private String sex;
public static boolean flag=false;
public Res() {
super();
}
/**
* @return the flag
*/
public boolean isFlag() {
return flag;
}
/**
* @param flag the flag to set
*/
public void setFlag(boolean flag) {
this.flag = flag;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the sex
*/
public String getSex() {
return sex;
}
/**
* @param sex the sex to set
*/
public void setSex(String sex) {
this.sex = sex;
}
}
class InputThread extends Thread{
Res res;
public InputThread(Res res) {
super();
this.res = res;
}
@Override
public void run() {
int count=0;
while(true){
synchronized (res) {
if(Res.flag){//是true,代表写了的,读线程还没都,那么我wait一下释放锁,进入等待阻塞中
try {
res.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(count%2==0){
res.setName("余秋雨");
res.setSex("男");
}else{
res.setName("小红");
res.setSex("女");
}
Res.flag=true;
count+=1;
res.notifyAll();
}
}
}
}
class OnputThread extends Thread{
Res res;
public OnputThread(Res res) {
super();
this.res = res;
}
@Override
public void run() {
while(true){
synchronized (res) {
if(!Res.flag){//如果flag为fasle,代表已读,生成线程还没造新数据
try {
res.wait();//wait可释放锁,让自己这个线程进入等待,
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(res.getName()+"--"+res.getSex());
Res.flag=false;
res.notifyAll();//notifyAll唤醒所有的 wait的锁,和wait配合使用
}
}
}
}
/**
* @author lqx
* 线程的之间通讯-synchronized同一把锁
* wait可释放锁,让自己这个线程进入等待,notifyAll唤醒所有的 wait的锁,和wait配合使用
*/
public class Thread3{
public static void main(String[] args) {
Res res = new Res();
InputThread inputThread = new InputThread(res);
OnputThread onputThread = new OnputThread(res);
inputThread.start();
onputThread.start();
}
}