两种常用的线程模型

两种线程模型:
      1、生产者-消费者模型 ,就是由一个线程生产任务,而另外一个线程执行任务,二个线程之间有一个共享数据区,这种数据结构可以用队列来表示,但是必须是并发同步的,也就是就共享数据队列同一时间只能允许一个线程进行访问。这种机制叫做同步访问,在JAVA里面用关键字synchorinized 来标识对象是同步并发访问的。

       生产者/消费者模式是一种很经典的线程同步模型,很多时候,并不是光保证多个线程对某共享资源操作的互斥性就够了,往往多个线程之间都是有协作的。
      2、线程池模型 ,就是说开始由值守线程创建N个工作线程,并启动它们,它们的状态初始为空闲。然后值守线程到工作队列中取出一个工作任务,同时从线程池中取出一空闲线程来执行此工作任务,执行完该任务后,把该工作线程由运行变为空闲状态,这样不断的从工作队列中取出任务由线程池中的空闲线程进行执行完成。线程池模型不用为每个任务都创建一个线程,只需初始时创建N个线程,然后一直用这N个线程去执行工作队列中的任务,大大的减少了线程的启动,终止的开销

      总之,多线程编程的关键是线程类的设计,以及共享数据的设计,同时注意区分哪些是多线程可能访问,哪些是各线程自已私有的,还有就是线程的状态变换,比如挂起的线程何时需要唤醒。等等问题。。

 

生产者-消费者模型:

实际上,准确说应该是“生产者-消费者-仓储”模型,离开了仓储,生产者消费者模型就显得没有说服力了。
对于此模型,应该明确一下几点:
1、生产者仅仅在仓储未满时候生产,仓满则停止生产。
2、消费者仅仅在仓储有产品时候才能消费,仓空则等待。
3、当消费者发现仓储没产品可消费时候会通知生产者生产。
4、生产者在生产出可消费产品时候,应该通知等待的消费者去消费。
 
此模型将要结合java.lang.Object的wait与notify、notifyAll方法来实现以上的需求。这是非常重要的。

Java代码 复制代码  收藏代码
  1. /**  
  2.  * 仓库   
  3.  */  
  4. public class Godown {   
  5.   
  6.     public static final int max_size = 100;  //最大库存量   
  7.     public int curnum;   //当前库存量   
  8.        
  9.     Godown(){   
  10.            
  11.     }   
  12.     Godown(int curnum){   
  13.         this.curnum = curnum;   
  14.     }   
  15.        
  16.      /**  
  17.      * 生产指定数量的产品   
  18.      * @param neednum  
  19.      */  
  20.     public synchronized void produce(int neednum) {   
  21.             //测试是否需要生产   
  22.             while (neednum + curnum > max_size) {   
  23.                     System.out.println("要生产的产品数量" + neednum + "超过剩余库存量" + (max_size - curnum) + ",暂时不能执行生产任务!");   
  24.                     try {   
  25.                             //当前的生产线程等待   
  26.                             wait();   
  27.                     } catch (InterruptedException e) {   
  28.                             e.printStackTrace();   
  29.                     }   
  30.             }   
  31.             //满足生产条件,则进行生产,这里简单的更改当前库存量   
  32.             curnum += neednum;   
  33.             System.out.println("已经生产了" + neednum + "个产品,现仓储量为" + curnum);   
  34.             //唤醒在此对象监视器上等待的所有线程   
  35.             notifyAll();   
  36.     }   
  37.   
  38.     /**  
  39.      * 消费指定数量的产品   
  40.      * @param neednum  
  41.      */  
  42.     public synchronized void consume(int neednum) {   
  43.             //测试是否可消费   
  44.             while (curnum < neednum) {   
  45.                     try {   
  46.                             wait();   
  47.                     } catch (InterruptedException e) {   
  48.                             e.printStackTrace();   
  49.                     }   
  50.             }   
  51.             //满足消费条件,则进行消费,这里简单的更改当前库存量   
  52.             curnum -= neednum;   
  53.             System.out.println("已经消费了" + neednum + "个产品,现仓储量为" + curnum);   
  54.             //唤醒在此对象监视器上等待的所有线程   
  55.             notifyAll();   
  56.     }    
  57. }  
/**
 * 仓库 
 */
public class Godown {

	public static final int max_size = 100;  //最大库存量
	public int curnum;   //当前库存量
	
	Godown(){
		
	}
	Godown(int curnum){
		this.curnum = curnum;
	}
	
	 /**
     * 生产指定数量的产品 
     * @param neednum
     */
    public synchronized void produce(int neednum) {
            //测试是否需要生产
            while (neednum + curnum > max_size) {
                    System.out.println("要生产的产品数量" + neednum + "超过剩余库存量" + (max_size - curnum) + ",暂时不能执行生产任务!");
                    try {
                            //当前的生产线程等待
                            wait();
                    } catch (InterruptedException e) {
                            e.printStackTrace();
                    }
            }
            //满足生产条件,则进行生产,这里简单的更改当前库存量
            curnum += neednum;
            System.out.println("已经生产了" + neednum + "个产品,现仓储量为" + curnum);
            //唤醒在此对象监视器上等待的所有线程
            notifyAll();
    }

    /**
     * 消费指定数量的产品 
     * @param neednum
     */
    public synchronized void consume(int neednum) {
            //测试是否可消费
            while (curnum < neednum) {
                    try {
                            wait();
                    } catch (InterruptedException e) {
                            e.printStackTrace();
                    }
            }
            //满足消费条件,则进行消费,这里简单的更改当前库存量
            curnum -= neednum;
            System.out.println("已经消费了" + neednum + "个产品,现仓储量为" + curnum);
            //唤醒在此对象监视器上等待的所有线程
            notifyAll();
    } 
}

 

Java代码 复制代码  收藏代码
  1. /**  
  2.  * 生产者  
  3.  */  
  4. public class Producer extends Thread{   
  5.   
  6.     private int neednum;  //生产产品的数量   
  7.     private Godown godown; //仓库   
  8.        
  9.     Producer(){   
  10.            
  11.     }   
  12.     Producer(int neednum,Godown godown){   
  13.         this.neednum = neednum;   
  14.         this.godown = godown;   
  15.     }   
  16.        
  17.     public void run() {   
  18.           //生产指定数量的产品   
  19.         godown.produce(neednum);   
  20.     }   
  21. }  
/**
 * 生产者
 */
public class Producer extends Thread{

	private int neednum;  //生产产品的数量
	private Godown godown; //仓库
	
	Producer(){
		
	}
	Producer(int neednum,Godown godown){
		this.neednum = neednum;
		this.godown = godown;
	}
	
	public void run() {
		  //生产指定数量的产品
		godown.produce(neednum);
	}
}

 

Java代码 复制代码  收藏代码
  1. /**  
  2. * 消费者  
  3. */  
  4. public class Consumer extends Thread{   
  5.   
  6.     private int neednum;   
  7.     private Godown godown;   
  8.        
  9.     Consumer(){   
  10.            
  11.     }   
  12.     Consumer(int neednum, Godown godown){   
  13.         this.neednum = neednum;   
  14.         this.godown = godown;   
  15.     }   
  16.     public void run(){   
  17.          //消费指定数量的产品   
  18.         godown.consume(neednum);   
  19.     }   
  20. }  
/**
* 消费者
*/
public class Consumer extends Thread{

	private int neednum;
	private Godown godown;
	
	Consumer(){
		
	}
	Consumer(int neednum, Godown godown){
		this.neednum = neednum;
		this.godown = godown;
	}
	public void run(){
		 //消费指定数量的产品
		godown.consume(neednum);
	}
}

 

Java代码 复制代码  收藏代码
  1. public class ThreadTest {   
  2.   
  3.     public static void main(String[] args) {   
  4.          Godown godown = new Godown(30);   
  5.          Consumer c1 = new Consumer(50, godown);   
  6.          Consumer c2 = new Consumer(20, godown);   
  7.          Consumer c3 = new Consumer(30, godown);   
  8.          Producer p1 = new Producer(10, godown);   
  9.          Producer p2 = new Producer(10, godown);   
  10.          Producer p3 = new Producer(10, godown);   
  11.          Producer p4 = new Producer(10, godown);   
  12.          Producer p5 = new Producer(10, godown);   
  13.          Producer p6 = new Producer(10, godown);   
  14.          Producer p7 = new Producer(80, godown);   
  15.          Producer p8 = new Producer(10, godown);   
  16.   
  17.          c1.start();  //wait   
  18.          c2.start();     
  19.          c3.start();  //wait     
  20.          p1.start();   
  21.          p2.start();  //p2执行完后,仓储量为30,唤醒等待线程时,c3在等待且消费数量满足要求,故又执行c3   
  22.                       //已经生产了10个产品,现仓储量为30   
  23.                       //已经消费了30个产品,现仓储量为0   
  24.          p3.start();   
  25.          p4.start();   
  26.          p5.start();   
  27.          p6.start();   
  28.          p7.start(); //wait   
  29.                      //要生产的产品数量80超过剩余库存量60,暂时不能执行生产任务!   
  30.          p8.start();   
  31.     }   
  32. }  
public class ThreadTest {

	public static void main(String[] args) {
		 Godown godown = new Godown(30);
         Consumer c1 = new Consumer(50, godown);
         Consumer c2 = new Consumer(20, godown);
         Consumer c3 = new Consumer(30, godown);
         Producer p1 = new Producer(10, godown);
         Producer p2 = new Producer(10, godown);
         Producer p3 = new Producer(10, godown);
         Producer p4 = new Producer(10, godown);
         Producer p5 = new Producer(10, godown);
         Producer p6 = new Producer(10, godown);
         Producer p7 = new Producer(80, godown);
         Producer p8 = new Producer(10, godown);

         c1.start();  //wait
         c2.start();  
         c3.start();  //wait  
         p1.start();
         p2.start();  //p2执行完后,仓储量为30,唤醒等待线程时,c3在等待且消费数量满足要求,故又执行c3
                      //已经生产了10个产品,现仓储量为30
         			  //已经消费了30个产品,现仓储量为0
         p3.start();
         p4.start();
         p5.start();
         p6.start();
         p7.start(); //wait
          			 //要生产的产品数量80超过剩余库存量60,暂时不能执行生产任务!
         p8.start();
	}
}

 结果:

已经消费了20个产品,现仓储量为10
已经生产了10个产品,现仓储量为20
已经生产了10个产品,现仓储量为30
已经消费了30个产品,现仓储量为0
已经生产了10个产品,现仓储量为10
已经生产了10个产品,现仓储量为20
已经生产了10个产品,现仓储量为30
已经生产了10个产品,现仓储量为40
要生产的产品数量80超过剩余库存量60,暂时不能执行生产任务!
已经生产了10个产品,现仓储量为50
要生产的产品数量80超过剩余库存量50,暂时不能执行生产任务!
已经消费了50个产品,现仓储量为0
已经生产了80个产品,现仓储量为80

 

API例子:

Java代码 复制代码  收藏代码
  1. /*Usage example, based on a typical producer-consumer scenario.   
  2.  * Note that a <tt>BlockingQueue</tt> can safely be used with multiple   
  3.  * producers and multiple consumers.   
  4.  * /   
  5.     
  6. class Producer implements Runnable {   
  7.   private final BlockingQueue queue;   
  8.   Producer(BlockingQueue q) { queue = q; }   
  9.   public void run() {   
  10.     try {   
  11.       while (true) { queue.put(produce()); }   
  12.     } catch (InterruptedException ex) { ... handle ...}   
  13.   }   
  14.   Object produce() { ... }   
  15. }   
  16.   
  17. class Consumer implements Runnable {   
  18.   private final BlockingQueue queue;   
  19.   Consumer(BlockingQueue q) { queue = q; }   
  20.   public void run() {   
  21.     try {   
  22.       while (true) { consume(queue.take()); }   
  23.     } catch (InterruptedException ex) { ... handle ...}   
  24.   }   
  25.   void consume(Object x) { ... }   
  26. }   
  27.   
  28. class Setup {   
  29.   void main() {   
  30.     BlockingQueue q = new SomeQueueImplementation();   
  31.     Producer p = new Producer(q);   
  32.     Consumer c1 = new Consumer(q);   
  33.     Consumer c2 = new Consumer(q);   
  34.     new Thread(p).start();   
  35.     new Thread(c1).start();   
  36.     new Thread(c2).start();   
  37.   }   
  38. }  
/*Usage example, based on a typical producer-consumer scenario.
 * Note that a <tt>BlockingQueue</tt> can safely be used with multiple
 * producers and multiple consumers.
 * /
 
class Producer implements Runnable {
  private final BlockingQueue queue;
  Producer(BlockingQueue q) { queue = q; }
  public void run() {
    try {
      while (true) { queue.put(produce()); }
    } catch (InterruptedException ex) { ... handle ...}
  }
  Object produce() { ... }
}

class Consumer implements Runnable {
  private final BlockingQueue queue;
  Consumer(BlockingQueue q) { queue = q; }
  public void run() {
    try {
      while (true) { consume(queue.take()); }
    } catch (InterruptedException ex) { ... handle ...}
  }
  void consume(Object x) { ... }
}

class Setup {
  void main() {
    BlockingQueue q = new SomeQueueImplementation();
    Producer p = new Producer(q);
    Consumer c1 = new Consumer(q);
    Consumer c2 = new Consumer(q);
    new Thread(p).start();
    new Thread(c1).start();
    new Thread(c2).start();
  }
}

 

 

  example2:

假设有这样一种情况,有一个桌子,桌子上面有一个盘子,盘子里只能放一颗鸡蛋,A专门往盘子里放鸡蛋,如果盘子里有鸡蛋,则一直等到盘子里没鸡蛋,B专门从盘子里拿鸡蛋,如果盘子里没鸡蛋,则等待直到盘子里有鸡蛋。其实盘子就是一个互斥区,每次往盘子放鸡蛋应该都是互斥的,A的等待其实就是主动放弃锁,B 等待时还要提醒A放鸡蛋。
如何让线程主动释放锁
很简单,调用锁的wait()方法就好。wait方法是从Object来的,所以任意对象都有这个方法。
声明一个盘子,只能放一个鸡蛋

Java代码 复制代码  收藏代码
  1. import java.util.ArrayList;   
  2. import java.util.List;   
  3.   
  4. public class Plate {   
  5.   
  6.     List<Object> eggs = new ArrayList<Object>();   
  7.   
  8.     public synchronized Object getEgg() {   
  9.         if (eggs.size() == 0) {   
  10.             try {   
  11.                 wait();   
  12.             } catch (InterruptedException e) {   
  13.             }   
  14.         }   
  15.   
  16.         Object egg = eggs.get(0);   
  17.         eggs.clear();// 清空盘子   
  18.         notify();// 唤醒阻塞队列的某线程到就绪队列   
  19.         System.out.println("拿到鸡蛋");   
  20.         return egg;   
  21.     }   
  22.   
  23.     public synchronized void putEgg(Object egg) {   
  24.         if (eggs.size() > 0) {   
  25.             try {   
  26.                 wait();   
  27.             } catch (InterruptedException e) {   
  28.             }   
  29.         }   
  30.         eggs.add(egg);// 往盘子里放鸡蛋   
  31.         notify();// 唤醒阻塞队列的某线程到就绪队列   
  32.         System.out.println("放入鸡蛋");   
  33.     }   
  34.        
  35.     static class AddThread extends Thread{   
  36.         private Plate plate;   
  37.         private Object egg=new Object();   
  38.         public AddThread(Plate plate){   
  39.             this.plate=plate;   
  40.         }   
  41.            
  42.         public void run(){   
  43.             for(int i=0;i<5;i++){   
  44.                 plate.putEgg(egg);   
  45.             }   
  46.         }   
  47.     }   
  48.        
  49.     static class GetThread extends Thread{   
  50.         private Plate plate;   
  51.         public GetThread(Plate plate){   
  52.             this.plate=plate;   
  53.         }   
  54.            
  55.         public void run(){   
  56.             for(int i=0;i<5;i++){   
  57.                 plate.getEgg();   
  58.             }   
  59.         }   
  60.     }   
  61.        
  62.     public static void main(String args[]){   
  63.         try {   
  64.             Plate plate=new Plate();   
  65.             Thread add=new Thread(new AddThread(plate));   
  66.             Thread get=new Thread(new GetThread(plate));   
  67.             add.start();   
  68.             get.start();   
  69.             add.join();   
  70.             get.join();   
  71.         } catch (InterruptedException e) {   
  72.             e.printStackTrace();   
  73.         }   
  74.         System.out.println("测试结束");   
  75.     }   
  76. }  
import java.util.ArrayList;
import java.util.List;

public class Plate {

    List<Object> eggs = new ArrayList<Object>();

    public synchronized Object getEgg() {
        if (eggs.size() == 0) {
            try {
                wait();
            } catch (InterruptedException e) {
            }
        }

        Object egg = eggs.get(0);
        eggs.clear();// 清空盘子
        notify();// 唤醒阻塞队列的某线程到就绪队列
        System.out.println("拿到鸡蛋");
        return egg;
    }

    public synchronized void putEgg(Object egg) {
        if (eggs.size() > 0) {
            try {
                wait();
            } catch (InterruptedException e) {
            }
        }
        eggs.add(egg);// 往盘子里放鸡蛋
        notify();// 唤醒阻塞队列的某线程到就绪队列
        System.out.println("放入鸡蛋");
    }
    
    static class AddThread extends Thread{
        private Plate plate;
        private Object egg=new Object();
        public AddThread(Plate plate){
            this.plate=plate;
        }
        
        public void run(){
            for(int i=0;i<5;i++){
                plate.putEgg(egg);
            }
        }
    }
    
    static class GetThread extends Thread{
        private Plate plate;
        public GetThread(Plate plate){
            this.plate=plate;
        }
        
        public void run(){
            for(int i=0;i<5;i++){
                plate.getEgg();
            }
        }
    }
    
    public static void main(String args[]){
        try {
            Plate plate=new Plate();
            Thread add=new Thread(new AddThread(plate));
            Thread get=new Thread(new GetThread(plate));
            add.start();
            get.start();
            add.join();
            get.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("测试结束");
    }
}

 

 结果:

放入鸡蛋
拿到鸡蛋
放入鸡蛋
拿到鸡蛋
放入鸡蛋
拿到鸡蛋
放入鸡蛋
拿到鸡蛋
放入鸡蛋
拿到鸡蛋
测试结束

 

声明一个Plate对象为plate,被线程A和线程B共享,A专门放鸡蛋,B专门拿鸡蛋。假设
1 开始,A调用plate.putEgg方法,此时eggs.size()为0,因此顺利将鸡蛋放到盘子,还执行了notify()方法,唤醒锁的阻塞队列的线程,此时阻塞队列还没有线程。
2 又有一个A线程对象调用plate.putEgg方法,此时eggs.size()不为0,调用wait()方法,自己进入了锁对象的阻塞队列。
3 此时,来了一个B线程对象,调用plate.getEgg方法,eggs.size()不为0,顺利的拿到了一个鸡蛋,还执行了notify()方法,唤醒锁的阻塞队列的线程,此时阻塞队列有一个A线程对象,唤醒后,它进入到就绪队列,就绪队列也就它一个,因此马上得到锁,开始往盘子里放鸡蛋,此时盘子是空的,因此放鸡蛋成功。
4 假设接着来了线程A,就重复2;假设来料线程B,就重复3。
整个过程都保证了放鸡蛋,拿鸡蛋,放鸡蛋,拿鸡蛋。

参考:http://www.iteye.com/topic/806990

 

 

Example3:

题目为:
有一个南北向的桥,只能容纳一个人,现桥的两边分别有10人和12人,编制一个多线程序让这些人到达对岸,每个人用一个线程表示,桥为共享资源。在过桥的过程中显示谁在过桥及其走向

论坛链接:http://www.iteye.com/topic/1041415

解法如下:
桥是共享资源,采用单例

Java代码 复制代码  收藏代码
  1. public enum Direction {     
  2.          
  3.     North2Sourth{     
  4.         String getInfo(){     
  5.             return "北向南走";     
  6.         }     
  7.     },     
  8.     Sourth2North{     
  9.         String getInfo(){     
  10.             return "南向北走";     
  11.         }     
  12.     };     
  13.          
  14.     abstract String getInfo();     
  15.      
  16. }   
 public enum Direction {  
       
     North2Sourth{  
         String getInfo(){  
             return "北向南走";  
         }  
     },  
     Sourth2North{  
         String getInfo(){  
             return "南向北走";  
         }  
     };  
       
     abstract String getInfo();  
   
 } 

 

Java代码 复制代码  收藏代码
  1.  public class Person implements Runnable {     
  2.      /**   
  3.       * 方向   
  4.       */     
  5.      private Direction direction;     
  6.      /**   
  7.       * 姓名*标志   
  8.       */     
  9.      private String name;     
  10.     /**   
  11.      * 持有一个桥的引用   
  12.      */     
  13.     private static final Bridge BRIDGE=Bridge.getIntance();     
  14.     public Direction getDirection() {     
  15.         return direction;     
  16.     }     
  17.     public void setDirection(Direction direction) {     
  18.         this.direction = direction;     
  19.     }     
  20.     public String getName() {     
  21.         return name;     
  22.     }     
  23.     public void setName(String name) {     
  24.         this.name = name;     
  25.     }     
  26.     public void run() {     
  27.         BRIDGE.display(this);     
  28.     }     
  29.               
  30. }    
    public class Person implements Runnable {  
        /** 
         * 方向 
         */  
        private Direction direction;  
        /** 
         * 姓名*标志 
         */  
        private String name;  
       /** 
        * 持有一个桥的引用 
        */  
       private static final Bridge BRIDGE=Bridge.getIntance();  
       public Direction getDirection() {  
           return direction;  
       }  
       public void setDirection(Direction direction) {  
           this.direction = direction;  
       }  
       public String getName() {  
           return name;  
       }  
       public void setName(String name) {  
           this.name = name;  
       }  
       public void run() {  
           BRIDGE.display(this);  
       }  
              
   }  

 

Java代码 复制代码  收藏代码
  1. public class Bridge {     
  2.           
  3.      private static class BridgeContainer{     
  4.          private static Bridge intance=new Bridge();     
  5.      }     
  6.       
  7.      private Bridge(){     
  8.               
  9.      }     
  10.      public synchronized void display(Person p) {     
  11.          DateFormat df = new SimpleDateFormat("HH:mm:ss");     
  12.       
  13.          String date = df.format(System.currentTimeMillis());     
  14.       
  15.          System.out.println("时间:" + date+"过桥人为" +p.getName()+"方向是:"+ p.getDirection().getInfo() );     
  16.          try {     
  17.              /**   
  18.               * 模拟过桥过程   
  19.               */     
  20.              Thread.sleep(2000);     
  21.          } catch (InterruptedException e) {     
  22.              // TODO Auto-generated catch block     
  23.              e.printStackTrace();     
  24.          }     
  25.      }     
  26.           
  27.      public static Bridge  getIntance(){     
  28.          return BridgeContainer.intance;     
  29.      }     
  30.           
  31.       
  32.  }   
public class Bridge {  
       
     private static class BridgeContainer{  
         private static Bridge intance=new Bridge();  
     }  
   
     private Bridge(){  
           
     }  
     public synchronized void display(Person p) {  
         DateFormat df = new SimpleDateFormat("HH:mm:ss");  
   
         String date = df.format(System.currentTimeMillis());  
   
         System.out.println("时间:" + date+"过桥人为" +p.getName()+"方向是:"+ p.getDirection().getInfo() );  
         try {  
             /** 
              * 模拟过桥过程 
              */  
             Thread.sleep(2000);  
         } catch (InterruptedException e) {  
             // TODO Auto-generated catch block  
             e.printStackTrace();  
         }  
     }  
       
     public static Bridge  getIntance(){  
         return BridgeContainer.intance;  
     }  
       
   
 } 

 

Java代码 复制代码  收藏代码
  1. public class Client {     
  2.      public static void main(String[] args) {     
  3.          /**   
  4.           * 模拟在南边的12个   
  5.           */     
  6.          Person[] p1s=new Person[12];     
  7.          for(int i=0;i<12;i++){     
  8.              p1s[i]=new Person();     
  9.              p1s[i].setName("n"+i+"号");     
  10.              p1s[i].setDirection(Direction.North2Sourth);     
  11.              new Thread(p1s[i]).start();     
  12.          }     
  13.          /**   
  14.           * 模拟在北边的10个   
  15.           */     
  16.          Person[] p2s=new Person[10];     
  17.          for(int i=0;i<10;i++){     
  18.              p2s[i]=new Person();     
  19.              p2s[i].setName("s"+i+"号");     
  20.              p2s[i].setDirection(Direction.Sourth2North);     
  21.              new Thread(p2s[i]).start();     
  22.          }     
  23.      }     
  24.           
  25.       
  26.  }  
public class Client {  
     public static void main(String[] args) {  
         /** 
          * 模拟在南边的12个 
          */  
         Person[] p1s=new Person[12];  
         for(int i=0;i<12;i++){  
             p1s[i]=new Person();  
             p1s[i].setName("n"+i+"号");  
             p1s[i].setDirection(Direction.North2Sourth);  
             new Thread(p1s[i]).start();  
         }  
         /** 
          * 模拟在北边的10个 
          */  
         Person[] p2s=new Person[10];  
         for(int i=0;i<10;i++){  
             p2s[i]=new Person();  
             p2s[i].setName("s"+i+"号");  
             p2s[i].setDirection(Direction.Sourth2North);  
             new Thread(p2s[i]).start();  
         }  
     }  
       
   
 }

 运行结果如下:

Java代码 复制代码  收藏代码
  1. 时间:13:09:21过桥人为n0号方向是:北向南走     
  2.  时间:13:09:23过桥人为s9号方向是:南向北走     
  3.  时间:13:09:25过桥人为s8号方向是:南向北走     
  4.  时间:13:09:27过桥人为s7号方向是:南向北走     
  5.  时间:13:09:29过桥人为s5号方向是:南向北走     
  6.  时间:13:09:31过桥人为s6号方向是:南向北走     
  7.  时间:13:09:33过桥人为s4号方向是:南向北走     
  8.  时间:13:09:35过桥人为n10号方向是:北向南走     
  9.  时间:13:09:37过桥人为s0号方向是:南向北走     
  10.  时间:13:09:39过桥人为n11号方向是:北向南走     
  11.  时间:13:09:41过桥人为s2号方向是:南向北走     
  12.  时间:13:09:43过桥人为s3号方向是:南向北走     
  13.  时间:13:09:45过桥人为n8号方向是:北向南走     
  14.  时间:13:09:47过桥人为n6号方向是:北向南走     
  15.  时间:13:09:49过桥人为n9号方向是:北向南走     
  16.  时间:13:09:51过桥人为n2号方向是:北向南走     
  17.  时间:13:09:53过桥人为s1号方向是:南向北走     
  18.  时间:13:09:55过桥人为n4号方向是:北向南走     
  19.  时间:13:09:57过桥人为n7号方向是:北向南走     
  20.  时间:13:09:59过桥人为n5号方向是:北向南走     
  21.  时间:13:10:01过桥人为n1号方向是:北向南走     
  22.  时间:13:10:03过桥人为n3号方向是:北向南走  
时间:13:09:21过桥人为n0号方向是:北向南走  
 时间:13:09:23过桥人为s9号方向是:南向北走  
 时间:13:09:25过桥人为s8号方向是:南向北走  
 时间:13:09:27过桥人为s7号方向是:南向北走  
 时间:13:09:29过桥人为s5号方向是:南向北走  
 时间:13:09:31过桥人为s6号方向是:南向北走  
 时间:13:09:33过桥人为s4号方向是:南向北走  
 时间:13:09:35过桥人为n10号方向是:北向南走  
 时间:13:09:37过桥人为s0号方向是:南向北走  
 时间:13:09:39过桥人为n11号方向是:北向南走  
 时间:13:09:41过桥人为s2号方向是:南向北走  
 时间:13:09:43过桥人为s3号方向是:南向北走  
 时间:13:09:45过桥人为n8号方向是:北向南走  
 时间:13:09:47过桥人为n6号方向是:北向南走  
 时间:13:09:49过桥人为n9号方向是:北向南走  
 时间:13:09:51过桥人为n2号方向是:北向南走  
 时间:13:09:53过桥人为s1号方向是:南向北走  
 时间:13:09:55过桥人为n4号方向是:北向南走  
 时间:13:09:57过桥人为n7号方向是:北向南走  
 时间:13:09:59过桥人为n5号方向是:北向南走  
 时间:13:10:01过桥人为n1号方向是:北向南走  
 时间:13:10:03过桥人为n3号方向是:北向南走

 

 

2、线程池

在什么情况下使用线程池?
    1.单个任务处理的时间比较短
    2.将需处理的任务的数量大

使用线程池的好处:
    1.减少在创建和销毁线程上所花的时间
    2.如不使用线程池,有可能造成系统因创建大量线程而消耗完内存

 

http://xtu-xiaoxin.iteye.com/blog/647580

http://hi.baidu.com/fgfd0/blog/item/1fef52df03ba281f4954033b.html

转载自http://uule.iteye.com/blog/1101255

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值