JAVA中synchronized与wait、notify的使用
代码目的:由两个线程分别控制PrintMessages 类中成员变量的赋值和打印,并交替打印出“熊大”+“男”和“xionger”+“nv”。
本文属于对synchronized(resource)和wait、notify的练习。
其中:wait、notify方法必须在synchronized(resource)大括号内使用,因为需要锁对象来调用wait、notify方法。如resource.wait()和resource.notify()。
同时若需使两个线程交替运行,还需加一个标志位flag来确保线程的交替运行。
首先添加两个继承Runnable接口的类
//赋值线程
public class ThreadInput implements Runnable{
PrintMessages r;
public ThreadInput(PrintMessages r){
this.r=r;
}
@Override
public void run() {
int i =0;
while(true){
synchronized (r) { //共享一个锁对象r,即mian方法传到构造中的引用对象。
if(!r.flag) {
try {
r.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(i%2==0){
r.name="熊大";
r.sex ="男";
}else{
r.name="xionger";
r.sex ="nv";
}
i++;
r.flag=false;
r.notifyAll();
}
}
}
//打印线程
public class TheadOutput implements Runnable {
PrintMessages r;
public TheadOutput(PrintMessages r){
this.r=r;
}
public void run() {
while(true)
{
synchronized(r) {
if(r.flag==true)
{
try{r.wait();}catch(Exception e){};
}
//交替打印熊大 男 xionger nv
System.out.println(r.name+"....."+r.sex);
r.flag=true;
r.notifyAll();
//此时可以用notify也可以用notifyAll,notify为随机唤醒一个休眠线程。
//notifyall是唤醒所有线程。因为此时除主线程外总共两个线程,所以没关系。
}
}
}
}
}
//添加类,里面包含拥有成员name 和 sex以及flag
public class PrintMessages {
public String name;
public String sex;
public boolean flag=true;
}
//实现代码
public class ThreadCommunicationDemo {
public static void main(String[] args) {
PrintMessages r =new PrintMessages();
Runnable a =new ThreadInput(r);
Runnable b =new TheadOutput(r); //注意两个实现类共用一个对象r。
Thread c =new Thread(a);
Thread d =new Thread(b);
c.start();
d.start();
}
}