i007.cc

i007.cc

优先队列-降维打击

两种常用的线程模型

两种常用的线程模型

原创 2017年04月13日 10:23:32

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

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

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

 

生产者-消费者模型:

实际上,准确说应该是“生产者-消费者-仓储”模型,离开了仓储,生产者消费者模型就显得没有说服力了。
对于此模型,应该明确一下几点:
1、生产者仅仅在仓储未满时候生产,仓满则停止生产。
2、消费者仅仅在仓储有产品时候才能消费,仓空则等待。
3、当消费者发现仓储没产品可消费时候会通知生产者生产。
4、生产者在生产出可消费产品时候,应该通知等待的消费者去消费。

此模型将要结合java.lang.Object的wait与notify、notifyAll方法来实现以上的需求。这是非常重要的。

[java] view plain copy

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

 

[java] view plain copy

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

 

[java] view plain copy

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

 

[java] view plain copy

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

结果:

已经消费了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] view plain copy

  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. class Producer implements Runnable {
  6.   private final BlockingQueue queue;
  7.   Producer(BlockingQueue q) { queue = q; }
  8.   public void run() {
  9.     try {
  10.       while (true) { queue.put(produce()); }
  11.     } catch (InterruptedException ex) { … handle …}
  12.   }
  13.   Object produce() { … }
  14. }
  15. class Consumer implements Runnable {
  16.   private final BlockingQueue queue;
  17.   Consumer(BlockingQueue q) { queue = q; }
  18.   public void run() {
  19.     try {
  20.       while (true) { consume(queue.take()); }
  21.     } catch (InterruptedException ex) { … handle …}
  22.   }
  23.   void consume(Object x) { … }
  24. }
  25. class Setup {
  26.   void main() {
  27.     BlockingQueue q = new SomeQueueImplementation();
  28.     Producer p = new Producer(q);
  29.     Consumer c1 = new Consumer(q);
  30.     Consumer c2 = new Consumer(q);
  31.     new Thread(p).start();
  32.     new Thread(c1).start();
  33.     new Thread(c2).start();
  34.   }
  35. }

 

 

  example2:

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

[java] view plain copy

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

 

结果:

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

 

声明一个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] view plain copy

  1. public enum Direction {
  2.     North2Sourth{
  3.         String getInfo(){
  4.             return “北向南走”;
  5.         }
  6.     },
  7.     Sourth2North{
  8.         String getInfo(){
  9.             return “南向北走”;
  10.         }
  11.     };
  12.     abstract String getInfo();
  13. }

 

[java] view plain copy

  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. }

 

[java] view plain copy

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

 

[java] view plain copy

  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.  }

运行结果如下:

[java] view plain copy

  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号方向是:北向南走

 

 

2、线程池

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

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

 

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

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

发表回复