生产者和消费者例子太经典,将代码贴出,以备以后复习这种思想。
1.
package testing1;
public class ProAndCon1{
public static void main(String[] args){
Resourse r1 = new Resourse();
new Thread(new Producer1(r1)).start();
new Thread(new Producer1(r1)).start();
new Thread(new Conn1(r1)).start();
new Thread(new Conn1(r1)).start();
}
}
class Pro implements Runnable{
private Resourse r;
Pro(Resourse r){
this.r = r;
}
public void run( ){
while(true){
r.set("dandan");
}
}
}
class Conn1 implements Runnable{
private Resourse r;
Conn1(Resourse r){
this.r=r;
}
public void run(){
while(true){
r.out();
}
}
}
class Resourse{
private String name;
private int count;
private boolean flag = false;
public synchronized void set(String name){
while(flag)
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
this.name = name+"----"+count++;
System.out.println(Thread.currentThread().getName()+":生产者:"+this.name);
flag = true;
this.notifyAll();
}
public synchronized void out(){
while(!flag)
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"-----消费者--------"+ this.name);
flag = false;
this.notifyAll();
}
}
2.用到JDK 1.5新特性
package testing1;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ProAndCon2{
public static void main(String[] args){
Resourse r1 = new Resourse();
new Thread(new Pro(r1)).start();
new Thread(new Pro(r1)).start();
new Thread(new Conn1(r1)).start();
new Thread(new Conn1(r1)).start();
}
}
class Producer1 implements Runnable{
private Resourse r;
Producer1(Resourse r){
this.r = r;
}
public void run( ){
while(true){
try {
r.set("dandan");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class Conn1 implements Runnable{
private Resourse r;
Conn1(Resourse r){
this.r=r;
}
public void run(){
while(true){
try {
r.out();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class Resourse{
private String name;
private int count;
private boolean flag = false;
private Lock lock = new ReentrantLock();
private Condition condition_pro = lock.newCondition();
private Condition condition_con = lock.newCondition();
public void set(String name)throws Exception
{
lock.lock();
try {
while(flag)
condition_pro.await();
this.name = name+"----"+count++;
System.out.println(Thread.currentThread().getName()+":生产者:"+this.name);
flag = true;
condition_con.signal();
} finally{
lock.unlock();
}
}
public synchronized void out()throws Exception{
lock.lock();
try {
while(!flag)
condition_con.await();
System.out.println(Thread.currentThread().getName()+"-----消费者--------"+ this.name);
flag = false;
condition_pro.signal();
} finally{
lock.unlock();
}
}
}
---------------------- android培训、 java培训、期待与您交流! ----------------------详细请查看: http://edu.csdn.net/heima