------- android培训、java培训、期待与您交流! ----------
线程间通信:
线程间通讯:
就是多个线程操作同一个资源
操作动作不同
出现同步问题想前提
1,是否两个以上线程同时操作数据。
2,是否用同一个锁。
等待唤醒机制
notify唤醒:通常唤醒线程池中的第一个wait的线程
class Res
{
private String name;
private String sex;
private boolean flag;
public synchronized void set(String name,String sex)
{
if(flag)
try{this.wait();}catch(Exception e){}
this.name=name;
this.sex=sex;
flag=true;
this.notify();
}
public synchronized void out()
{
if(!flag)
try{this.wait();}catch(Exception e){}
System.out.println(name+"....."+sex);
flag=false;
this.notify();
}
}
class Input implements Runnable
{
private Res r;
Input(Res r)
{
this.r=r;
}
public void run()
{
int x=0;
while(true)
{
if(x==0)
r.set("mike","man");
else
r.set("lili","woman");
x=(x+1)%2;//切换
}
}
}
class Output implements Runnable
{
private Res r;
Output(Res r)
{
this.r=r;
}
public void run()
{
while(true)
{
r.out();
}
}
}
class InputOutputDemo
{
public static void main(String[] args)
{
Res r=new Res();
new Thread(new Input(r)).start();
new Thread(new Output(r)).start();
/*
Input i=new Input(r);
Output o=new Output(r);
Thread t1=new Thread(i);
Thread t2=new Thread(o);
t1.start();
t2.start();
*/
}
}
notifyAll();全部唤醒
wait();
notify();
notifyAll();
都是用在同步中,以为要对持有锁的线程操作。
所以要使用在同步中。
为什么他们定义在了Object类中?
因为上述三种方法操作同步线程时,都必须要标识他们所操作线程持有的锁,
等待和唤醒必须是同一个锁。
锁可以是任意对象,所以可以被任意对象调用的方法定义在Object类中。
生产者消费者例子
class ProducerConsumerDemo
{
public static void main(String[] args)
{
Resource r=new Resource();
Producer pro=new Producer(r);
Consumer con=new Consumer(r);
Thread t1=new Thread(pro);
Thread t2=new Thread(pro);
Thread t3=new Thread(con);
Thread t4=new Thread(con);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class Resource
{
private String name;
private int count=1;
private boolean flag=false;
private synchronized void set(String name)
{
while(flag)
try{wait();}catch(Exception e){}//
this.name=name+"..."+count++;
System.out.println(Thread.currentThread().getName()+"...生产者..."+this.name);
flag=true;
this.notifyAll();
}
public synchronized void out()
{
while(!flag)
try{wait();}catch(Exception e){}
System.out.println(Thread.currentThread().getName()+"...消费者......"+this.name);
flag=false;
this.notifyAll();
}
}
class Producer implements Runnable
{
Resource res;
Producer(Resource res)
{
this.res=res;
}
public void run()
{
while(true)
{
res.set("+商品+");
}
}
}
class Consumer implements Runnable
{
Resource res;
Consumer(Resource res)
{
this.res=res;
}
public void run()
{
while(true)
{
res.out();
}
}
}