一个线程类

来源:互联网 发布:公司网络监控能看到啥 编辑:程序博客网 时间:2024/05/22 01:58

package ch5;

public class Mythread {
   public static void main(String[] args){
    Queue q=new Queue();
    Producer p=new Producer(q);
       p.start();
    Consumer c=new Consumer(q);
       c.start();
   }
 
}
class Producer extends Thread
{
 Queue q;
 Producer(Queue q){
  this.q=q;
 }
 public void run(){
  for(int i=0;i<10;i++){
   q.put(i);
   System.out.println("Producer put :"+i);
  }
 }
}
class Consumer extends Thread
{
 Queue q;
 Consumer(Queue q){
  this.q=q;
 }
 public void run(){
  while(true){
   
   System.out.println("Producer get :"+q.get());
  }
 }
}

class Queue{
 int value;
 boolean bFull=false;
 
 public synchronized  void put(int i){
  if(!bFull)
  value=i;
  bFull=true;
  notify();
  try{
   wait();
  }catch(Exception e){
   e.printStackTrace();
  }
 }
 public synchronized  int get(){
   if(!bFull) 
  try{
   wait();
  }catch(Exception e){
   e.printStackTrace();
  }
  bFull=false;
  notify();
  return value;
 }
 

原创粉丝点击