文件在E:\学习文档子目录压缩\并发技术\J2SE多线程基础 或我的网盘\我的笔记\学习文档子目录压缩\并发技术\J2SE多线程基础下
ThreadLock1.java
package com.xiangshuai.thread;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class Res1{
private String name;
private String sex;
public static boolean flag=false;
public Lock lock=new ReentrantLock();
public Condition condition=lock.newCondition();
public Res1() {
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;
}
}
/**
* @author lqx
*生成对象线程
*/
class InputThread1 extends Thread{
Res1 res;
public InputThread1(Res1 res) {
super();
this.res = res;
}
@Override
public void run() {
int count=0;
while(true){
try {
res.lock.lock();
if(Res1.flag){//是true,代表写了的,读线程还没都,那么我wait一下释放锁,进入等待阻塞中
try {
System.out.println("等待前");
res.condition.await();
System.out.println("InputThread1等待15后需方锁");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(count%2==0){
res.setName("余秋雨");
res.setSex("男");
}else{
res.setName("小红");
res.setSex("女");
}
Res1.flag=true;
count+=1;
res.condition.signal();//相当于 notify
} catch (Exception e) {
e.printStackTrace();
}finally {
System.out.println("InputThread1需方锁");
res.lock.unlock();
}
}
}
}
/**
* @author Administrator
*消费线程
*/
class OnputThread1 extends Thread{
Res1 res;
public OnputThread1(Res1 res) {
super();
this.res = res;
}
@Override
public void run() {
while(true){
try {
res.lock.lock();
if(!Res1.flag){//如果flag为fasle,代表已读,生成线程还没造新数据
try {
res.condition.await();;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(res.getName()+"--"+res.getSex());
Res1.flag=false;
res.condition.signal();
} catch (Exception e) {
e.printStackTrace();
}finally {
System.out.println("OnputThread1需方锁");
res.lock.unlock();
}
}
}
}
/**
* @author lqx
* lock在多线程读操作时 可以随时获取锁进行操作-与synchronized不同,
* synchronized同一把锁永远只用一个线程在操作
* 因为是都所有不存在线程不安全的问题
* 因为wait只能在synchronized 使用所用这里用了lock.newCondition() 的 await() 和 signal
* 方法来 使线程等待和唤醒
*/
public class ThreadLock1{
public static void main(String[] args) {
Res1 res = new Res1();
InputThread1 inputThread = new InputThread1(res);
OnputThread1 onputThread = new OnputThread1(res);
inputThread.start();
onputThread.start();
}
}