要求:一个线程读数据,一个线程“取”数据,交替进行。
知识点:
1,多线程的等待唤醒机制
2,线程同步是这个机制的前提。
3,弄清楚为什么要加上this………….this.wait() this.notify()
4,wait()是原来的线程变成等待状态,notify()是唤醒内存线程池中第一个等待的线程。
5,等待唤醒机制要以同步为前提。原因:因为同步才会有监视器(或者说是锁,锁旗标),而线程的等待唤醒机制需要监视器才能对线程进行操作。
6,为什么这些操作线程的方法要定义在Object类中呢?
原因:同一个锁才能有同一个唤醒等待机制,而锁可以是任意对象,所以用Object。
package 多线程;
public class resources {
private String name;
private String sex;
private boolean flag = false;
public synchronized void set(String name,String sex)
{
if(flag)//==true;
try{this.wait();}catch(Exception e){}
this.name = name;
this.sex =sex;
flag= true;
this.notify();
}
public synchronized void get()
{
if(!flag)//==false;
try{this.wait();}catch(Exception e){}
System.out.println(name+"....."+sex);
flag =false;
this.notify();
}
}
package 多线程;
public class Input implements Runnable{
private resources res;
private int n=1;
Input(resources res)
{
this.res =res;
}
public void run()
{
while (true)
{
if(n==0)
res.set ("欧阳无敌" ,"男");
else
res.set ("Alina", "famale");
n=(n+1)%2;
}
}
}
package 多线程;
public class Output implements Runnable
{
private resources res;
public Output(resources res)
{
this.res = res;
}
public void run()
{
while(true)
{
res.get();
}
}
}
package 多线程;
public class 多线程通信小例子 {
public static void main(String[] args) {
// TODO 自动生成的方法存根
resources res = new resources();
new Thread(new Input(res)).start();
new Thread(new Output(res)).start();
/*Input in = new Input(res);
Output out = new Output(res);
Thread t1 = new Thread(in);
Thread t2 = new Thread(out);
t1.start();
t2.start();
*/
}
}