生产者和消费者

class Threaded
{
public static void main(String[] args)
{
C c = new C();

A a = new A(c);

B b = new B(c);

new Thread(a).start();

new Thread(b).start();
}
}


class A implements Runnable
{
C c = null;
public A(C c){
this.c = c;
}
public void run(){
for(int i = 0 ;i<10;i++){
if(i%2==0){
synchronized(this){
c.setC("生产者","开始生产");
}
}else{
synchronized(this){
c.setC("消费者","开始消费");
}
}
}
}
}



class B implements Runnable
{
C c = null;
public B(C c){
this.c = c;
}

public void run(){
for(int i=0;i<10;i++){
System.out.println(c.getC());
}
}
}


class C
{
String name ;
String info;
boolean fal = false;

public synchronized void setC(String name,String info){

if(fal){
try{
wait();
}catch(Exception e){
System.out.println("程序出错了....");
}
}
try{
Thread.sleep(1000);
}catch(Exception e){
System.out.println("非正常退出....");
}
this.name = name ;
this.info = info ;
notifyAll();
fal = true;

}



public synchronized String getC(){
if(!fal){
try{
wait();
}catch(Exception e){
System.out.println("程序出错了....");
}
}
try{
Thread.sleep(1000);
}catch(Exception e){
System.out.println("非正常退出....");
}
notifyAll();
fal = false;
return this.name+"\t"+this.info+"\n";
}

}

你可能感兴趣的:(thread,C++,c,C#)