public class ResourceDemo
{
public static void main(String args[]){
Resource r = new Resource();
Input input = new Input(r);
Output output = new Output(r);
Thread t1 = new Thread(input);
Thread t2 = new Thread(output);
t1.start();
t2.start();
}
}
class Resource{
String name;
String sex;
boolean flag = true;
}
class Input implements Runnable
{
private Resource r;
public Input(Resource r){
this.r = r;
}
public void run(){
int num = 0;
while(true){
synchronized(r){
if(!r.flag){
try{
System.out.println("input wait");
r.wait();//看r这个锁开了没有,开了就继续往下执行并占有r这个锁
System.out.println("input wait over");
}catch(Exception e){
}
}
if(num==0){
System.out.println("input lili");
r.name = "LiLi";
r.sex = "girl";
}else{
System.out.println("input DanDan");
r.name = "DanDan";
r.sex = "boy";
}
num = (num+1)%2;
try{
r.flag = false;
System.out.println("input notify");
r.notify();
}catch(Exception e){
}
}
}
}
}
class Output implements Runnable
{
private Resource r;
public Output(Resource r){
this.r = r;
}
public void run(){
while(true){
try{
System.out.println("sleep");
Thread.sleep(2000);
}catch(Exception e){
}
synchronized(r){
if(r.flag){
try{
System.out.println("output wait");
r.wait();
System.out.println("output wait over");
}catch(Exception e){
}
}
System.out.println(r.name+"--"+r.sex);
try{
r.flag = true;
//notify使wait线程变为阻塞
r.notify();//等notify所处的线程结束之后r这个锁才打开,其他r锁下的线程才执行
System.out.println("pre output notify");
Thread.sleep(2000);
System.out.println("end output notify");
}catch(Exception e){
}
}
}
}
}
{
public static void main(String args[]){
Resource r = new Resource();
Input input = new Input(r);
Output output = new Output(r);
Thread t1 = new Thread(input);
Thread t2 = new Thread(output);
t1.start();
t2.start();
}
}
class Resource{
String name;
String sex;
boolean flag = true;
}
class Input implements Runnable
{
private Resource r;
public Input(Resource r){
this.r = r;
}
public void run(){
int num = 0;
while(true){
synchronized(r){
if(!r.flag){
try{
System.out.println("input wait");
r.wait();//看r这个锁开了没有,开了就继续往下执行并占有r这个锁
System.out.println("input wait over");
}catch(Exception e){
}
}
if(num==0){
System.out.println("input lili");
r.name = "LiLi";
r.sex = "girl";
}else{
System.out.println("input DanDan");
r.name = "DanDan";
r.sex = "boy";
}
num = (num+1)%2;
try{
r.flag = false;
System.out.println("input notify");
r.notify();
}catch(Exception e){
}
}
}
}
}
class Output implements Runnable
{
private Resource r;
public Output(Resource r){
this.r = r;
}
public void run(){
while(true){
try{
System.out.println("sleep");
Thread.sleep(2000);
}catch(Exception e){
}
synchronized(r){
if(r.flag){
try{
System.out.println("output wait");
r.wait();
System.out.println("output wait over");
}catch(Exception e){
}
}
System.out.println(r.name+"--"+r.sex);
try{
r.flag = true;
//notify使wait线程变为阻塞
r.notify();//等notify所处的线程结束之后r这个锁才打开,其他r锁下的线程才执行
System.out.println("pre output notify");
Thread.sleep(2000);
System.out.println("end output notify");
}catch(Exception e){
}
}
}
}
}