等待唤醒机制极大地提高了cpu资源的利用,节约了时间
package com.xiaozhi.mythread;
/*
* 等待唤醒机制
* 等待和唤醒方法必须在锁内,因为是锁调用这两个方法
* 因为锁不固定,所以wait和notify是Object方法
*/
public class Test {
public static void main(String[] args) {
Res res=new Res();
Input input=new Input(res);
Output output=new Output(res);
Thread thread1=new Thread(input);
Thread thread2=new Thread(output);
thread1.start();
thread2.start();
}
}
class Res{
String name;
String sex;
boolean flag;
}
class Input implements Runnable{
private Res res;
private boolean flag=true;
public Input(Res res) {
super();
this.res = res;
}
@Override
public void run() {
while(true)
{
synchronized (res) {
if(res.flag)
{try {res.wait();} catch (InterruptedException e) {e.printStackTrace();}}
//输入
if(flag)
{
res.name="mike";
res.sex="man";
flag=false;
}else{
res.name="丽丽";
res.sex="女女女";
flag=true;
}
res.flag=true;
res.notify();
}
}
}
}
class Output implements Runnable{
private Res res;
public Output(Res res) {
super();
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.sex);
res.flag=false;
res.notify();
}
}
}
}
代码优化很重要
package com.xiaozhi.threadinformation;
/*
代码优化
*/
public class Test2 {
public static void main(String[] args) {
Res res=new Res();
Input input=new Input(res);
Output output=new Output(res);
Thread thread1=new Thread(input);
Thread thread2=new Thread(output);
thread1.start();
thread2.start();
}
}
class Res{
private String name;
private String sex;
private boolean resFlag=false;
public synchronized void input(String name,String sex)
{
if(resFlag)
{try {this.wait();} catch (InterruptedException e) {e.printStackTrace();}}
this.name=name;
this.sex=sex;
this.resFlag=true;
this.notify();
}
public synchronized void output()
{
if(!this.resFlag)
{try {this.wait();} catch (InterruptedException e) {e.printStackTrace();}}
//输出
System.out.println(this.name+"---------------"+this.sex);
this.resFlag=false;
this.notify();
}
}
class Input implements Runnable{
private Res res;
private boolean perFlag=true;
public Input(Res res) {
super();
this.res = res;
}
@Override
public void run() {
while(true)
{
if(perFlag)
{
res.input("mike","man");
perFlag=false;
}
else
{
res.input("丽丽","女女女");
perFlag=true;
}
}
}
}
class Output implements Runnable{
private Res res;
public Output(Res res) {
super();
this.res = res;
}
@Override
public void run() {
while(true)
res.output();
}
}