分类:java share 发布 2009.03.29 20:03:26Tag : java,php,Thread,Runnable commentComment:0
9
dig bury

在php中很少接触到有关进程的问题,以前在phpx上看到过一篇关于php进程的问题,隐约记得php是单线程

最佳学习java中接触到多线程的问题

接口 implements Runnable

继承 extends Thread

class Q
{
 String name = "unknow";
 String sex = "unknow";
 boolean bFull = false;
 
 public synchronized void put(String name,String sex)
 {
  if(bFull)
   try{
    wait();
   }catch(Exception e){
    
   }
   this.name = name;
   try{
    Thread.sleep(1);
   }catch(Exception e){
    
   }
   this.sex = sex;
   bFull = true;
   notify();
 }
 
 public synchronized void get()
 {
  if(!bFull)
   try{
    wait();
   }catch(Exception e){
    
   }
   System.out.print(name);
   System.out.println(":"+sex);
   bFull=false;
   notify();
 }
}


class Consumer implements Runnable{
 Q q;
 public Consumer(Q q)
 {
  this.q=q;
 }
 public void run()
 {
  while(true){
   q.get();
  }
 }
}

class Producer implements Runnable{
 Q q;
 public Producer(Q q)
 {
  this.q=q;
 }
 public void run()
 {
  int i=0;
  while(true)
  {
   if(i==0)
    q.put("zhangsan", "male");
   else
    q.put("lisi", "female");
   i=(i+1)%2;
  }
 }
}

public class lesson extends Thread
{
 public static void main(String [] args)
 {
  Q q = new Q();
  new Thread(new Producer(q)).start();
  new Thread(new Consumer(q)).start();
 }
}
 

我也来说2句,请不要发表违反法律的言论

姓名

Email(必填)

主页(不要加http://)