一种线程交互模型的实现

本文介绍一种采用线程交互模型,即主线程执行队列的Task,其他线程投递Task进入主线程的任务队列,投递方式类似于Win32 SDK的PostMessage和SendMessage方法,提供异步投递和同步投递。
首先我们需要一个BlockAndAwaitableQueue类,该类的功能是提供除执行Task线程外的其他线程的任务投递功能,该类包含一个任务列表,即存放待执行的Task。同时要考虑到多线程的同步问题,需要采用同步锁进行同步。同时要保证BlockAndAwaitableQueue的主执行线程在无Task可执行时不占用过多的系统资源需要实现一种monitor模型。即在没有Task可执行时,需要使该线程进入等待队列中,而在有Task投入进来时,需要唤醒Task列表中的等待队列中的当前执行线程。该模型有个限制,即所提交的Task不应占用过多的执行时间。
Java代码 复制代码
  1. public class BlockAndAwaitableQueue{   
  2.             private ArrayList taskList = new ArrayList();   
  3.                
  4.             private volatile boolean bStop = false;   
  5.                
  6.             private volatile boolean bRunning = false;   
  7.                            
  8.             private Thread runningThread;   
  9.                
  10.             Runnable finalTask = new Runnable()   
  11.             {   
  12.                 public void run()   
  13.                 {   
  14.                    System.out.println("runningThread will exit.");   
  15.                      
  16.                        synchronized (this) {                    
  17.                                                       
  18.                                bRunning = false;   
  19.                                   
  20.                                System.out.println("notify ...");   
  21.                                synchronized (runningThread) {   
  22.                                  runningThread.notifyAll();   
  23.                             }             
  24.                             
  25.                         }          
  26.                        System.out.println("runningThread exit.");   
  27.                 }   
  28.             };   
  29.             public BlockAndAwaitableQueue()   
  30.             {   
  31.                    
  32.             }   
  33.             /*  
  34.              * This can be called by runningThread and other threads.  
  35.              * @param task  The task wants to be executed asychronized.  
  36.              */  
  37.             public void addTask(Runnable task)   
  38.             {   
  39.                 synchronized(taskList)   
  40.                 {   
  41.                    taskList.add(task);   
  42.                    // notify   
  43.                    taskList.notifyAll();   
  44.                 }   
  45.              }   
  46.             /*  
  47.              * This can not be called by the runningThread  
  48.              */  
  49.              public void addTaskAndAwait(final Runnable task)   
  50.              {   
  51.                  if(runningThread == Thread.currentThread())   
  52.                  {   
  53.                      System.out.println("This can not be called by the runningThread");   
  54.                      return;   
  55.                  }   
  56.                     
  57.                  final Object latchObject = new Object();   
  58.                   synchronized(latchObject)   
  59.                   {   
  60.                       
  61.                     addTask(new Runnable(){   
  62.                      public void run()   
  63.                      {   
  64.                          task.run();   
  65.                          synchronized(latchObject)   
  66.                          {   
  67.                              latchObject.notify();   
  68.                          }                           
  69.                       }                       
  70.                      });   
  71.                     try {   
  72.                         latchObject.wait();   
  73.                     } catch (InterruptedException e) {                 
  74.                     }   
  75.                    }       
  76.              }   
  77.              public void stopInvocation()   
  78.              {   
  79.                 bStop = true;   
  80.                 addTask(finalTask);   
  81.              }   
  82.                 
  83.              public void stopInvocationAndAwait()   
  84.              {   
  85.                 bStop = true;   
  86.                 addTaskAndAwait(finalTask);   
  87.              }   
  88.                 
  89.              private void doInvocations()   
  90.              {   
  91.                  synchronized(taskList)   
  92.                  {   
  93.                     while(taskList.size() == 0)   
  94.                      {   
  95.                         try {                              
  96.                              taskList.wait();          
  97.                  } catch (InterruptedException e) {                
  98.                    }       
  99.                              }    
  100.                      for(int i=0; i < taskList.size(); i++)   
  101.                      {   
  102.                          Runnable task = (Runnable)taskList.get(i);   
  103.                          task.run();   
  104.                          task = null;   
  105.                       }   
  106.                      // clear the task list   
  107.                      taskList.clear();     
  108.                  }   
  109.               }   
  110.              public void run()   
  111.              {   
  112.                  synchronized (this) {   
  113.                      while(bRunning)   
  114.                      {   
  115.                            
  116.                         try {   
  117.                             System.out.println("await ...");   
  118.                             synchronized (runningThread) {   
  119.                                 runningThread.wait();   
  120.                             }                          
  121.                             System.out.println("await over");   
  122.                         } catch (InterruptedException e) {   
  123.                             // TODO Auto-generated catch block   
  124.                             e.printStackTrace();   
  125.                         }   
  126.                                
  127.                      }   
  128.                      bRunning = true;   
  129.                 }   
  130.                     
  131.                  runningThread = Thread.currentThread();   
  132.                     
  133.                  bStop = false;   
  134.      
  135.                  while(!bStop)   
  136.                   {   
  137.                       doInvocations();   
  138.                   }   
  139.              }   
  140.                 
  141.              public static void main(String[] args)   
  142.              {   
  143.                  final BlockAndAwaitableQueue taskQueue = new BlockAndAwaitableQueue();   
  144.                  new Thread(new Runnable(){   
  145.                      public void run()   
  146.                      {   
  147.                          taskQueue.run();   
  148.                             
  149.                      }   
  150.                  }).start();   
  151.                     
  152.                
  153.                     
  154.                  new Thread(new Runnable(){   
  155.                      public void run()   
  156.                      {   
  157.                          taskQueue.run();   
  158.                      }   
  159.                  }).start();   
  160.               
  161.                     
  162.                  new Thread(new Runnable(){   
  163.                      public void run()   
  164.                      {   
  165.                          taskQueue.addTaskAndAwait(new Runnable(){   
  166.                              public void run()   
  167.                              {   
  168.                                  System.out.println("Task ID#1 has been executed.");   
  169.                              }   
  170.                          });   
  171.                          System.out.println("After Task ID#1 has been executed.");   
  172.                      }   
  173.                  }).start();   
  174.                  new Thread(new Runnable(){   
  175.                      public void run()   
  176.                      {   
  177.                          taskQueue.addTask(new Runnable(){   
  178.                              public void run()   
  179.                              {   
  180.                                  System.out.println("Task ID#2 has been executed.");          
  181.                                  //stop the queue   
  182.                              }   
  183.                          });   
  184.                      }   
  185.                  }).start();   
  186.                     
  187.                  new Thread(new Runnable(){   
  188.                      public void run()   
  189.                      {   
  190.                               
  191.                         taskQueue.stopInvocationAndAwait();   
  192.                         taskQueue.stopInvocationAndAwait();   
  193.                                
  194.                      }   
  195.                        
  196.                  }).start();   
  197.                                     
  198.              }   
  199. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值