java开发多线程机制

来源:互联网 发布:如何不被淘宝品控 编辑:程序博客网 时间:2024/06/08 13:51

最近用JAVA开发并发多线程机制,一般我们开发的程序都是只有一个主线程的,即MAIN()函数开始,但是在一些特别的场合下,比如服务器接受命令的 过程,可能需要同时处理多个客户端发送的命令,这时就需要征对每个客户建立一个线程。这样建立多线程程序,多线程可以使得在同一时间间隔内,执行多个指 令,以至于多个逻辑处理并发的运行。在JAVA中有二种方法可以定义一个线程:Runnable接口与Thread类,最终都是由Thread类的 start()方法启动线程,而真正执行的命令在run()方法中,另外线程有几种状态:执行,终止,休眠,挂起等。在某种条件下各个状态之间可以互相转换。 
     

有二种比较重要模型:
      生产者-消费者模型,就是由一个线程生产任务,而另外一个线程执行任务,二个线程之间有一个共享数据区,这种数据结构可以用队列来表示,但是必须是并发同 步的,也就是就共享数据队列同一时间只能允许一个线程进行访问。这种机制叫做同步访问,在JAVA里面用关键字synchorinized 来标识对象是同步并发访问的。
      线程池模型,就是说开始由值守线程创建N个工作线程,并启动它们,它们的状态初始为空闲。然后值守线程到工作队列中取出一个工作任务,同时从线程池中取出 一空闲线程来执行此工作任务,执行完该任务后,把该工作线程由运行变为空闲状态,这样不断的从工作队列中取出任务由线程池中的空闲线程进行执行完成。线程 池模型不用为每个任务都创建一个线程,只需初始时创建N个线程,然后一直用这N个线程去执行工作队列中的任务,大大的减少了线程的启动,终止的开销。 

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

 

一个线程池模型的实例:

ThreadPool.java

[java] view plaincopy
  1. import java.util.ArrayList;  
  2. import java.util.Iterator;  
  3. import java.util.LinkedList;  
  4. import java.util.Timer;  
  5. public class ThreadPool  
  6. {    
  7.   private static final UtilProperties utilProp = new UtilProperties();  
  8.   private static int minPools = Integer.parseInt(utilProp  
  9.       .getValue("minPools"));  
  10.   private static int maxPools = Integer.parseInt(utilProp  
  11.       .getValue("maxPools"));  
  12.   private static int checkThreadPeriod = Integer.parseInt(utilProp  
  13.       .getValue("checkThreadPeriod")) * 60 * 1000;  
  14.   private static ArrayList<WorkerThread> workThreadList; //   
  15.   private static LinkedList<Work> taskList = null//   
  16.   private static int totalThread = 0//   
  17.   private static int freeThreadCount = 0//   
  18.   private java.util.Timer timer = null//   
  19.   private static Object o = new Object();  
  20.    
  21.   private static ThreadPool pool=new ThreadPool();  
  22.    
  23.   public static void setMinPools(int minPools)  
  24.   {  
  25.       ThreadPool.minPools = minPools;  
  26.   }  
  27.   public static void setMaxPools(int maxPools)  
  28.   {  
  29.       ThreadPool.maxPools = maxPools;  
  30.   }  
  31.   public static void setCheckThreadPeriod(int checkThreadPeriod)  
  32.   {  
  33.       ThreadPool.checkThreadPeriod = checkThreadPeriod;  
  34.   }  
  35.   private ThreadPool()  
  36.   {      
  37.       workThreadList = new ArrayList<WorkerThread>();  
  38.       taskList = new LinkedList<Work>();  
  39.       //  
  40.       for (int i = 0; i < ThreadPool.minPools; i++)  
  41.       {  
  42.         WorkerThread temp = new WorkerThread();  
  43.         totalThread = totalThread + 1;  
  44.         workThreadList.add(temp);  
  45.         temp.start();  
  46.         try  
  47.         {  
  48.           Thread.sleep(100);  
  49.         }  
  50.         catch (Exception e)  
  51.         {  
  52.         }  
  53.       }  
  54.       timer = new Timer(true); //   
  55.       timer.schedule(new CheckThreadTask(this), 0, checkThreadPeriod);  
  56.   }  
  57.    
  58.   public static ThreadPool getInstance()  
  59.   {  
  60.       return pool;  
  61.   }  
  62.    
  63.   public synchronized void run(Work work)  
  64.   {  
  65.       if (freeThreadCount == 0)  
  66.       {  
  67.         if (totalThread < maxPools)  
  68.         {  
  69.           WorkerThread temp = new WorkerThread();  
  70.           totalThread = totalThread + 1;  
  71.           workThreadList.add(temp);  
  72.           temp.start();  
  73.           synchronized (taskList)  
  74.           {  
  75.               taskList.add(work);  
  76.               taskList.notify();  
  77.           }  
  78.         }  
  79.         else  
  80.         {  
  81.           while (freeThreadCount == 0)  
  82.           {  
  83.               try  
  84.               {  
  85.                 Thread.sleep(200);  
  86.               }  
  87.               catch (InterruptedException e)  
  88.               {  
  89.               }  
  90.           }  
  91.           synchronized (taskList)  
  92.           {  
  93.             taskList.add(work);  
  94.             taskList.notify();  
  95.           }  
  96.         }  
  97.     }  
  98.     else  
  99.     {  
  100.         synchronized (taskList)  
  101.         {  
  102.           taskList.add(work);  
  103.           taskList.notify();  
  104.         }  
  105.     }  
  106.   }  
  107.   /** *//** 
  108.   *  
  109.   * 
  110.   */  
  111.   public synchronized void checkAllThreads()  
  112.   {  
  113.     Iterator<WorkerThread> threadIterator = workThreadList.iterator();  
  114.     while (threadIterator.hasNext())  
  115.     { //   
  116.         WorkerThread workThread = (WorkerThread) threadIterator.next();  
  117.         if (!(workThread.isAlive()))  
  118.         {  
  119.           //   
  120.           workThread = new WorkerThread(); //   
  121.           workThread.start(); //   
  122.         }  
  123.     }  
  124.   }  
  125.   public static void printInfo()  
  126.   {  
  127.     System.out.println("minPools:" + minPools);  
  128.     System.out.println("maxPools:" + maxPools);  
  129.     System.out.println("checkThreadPeriod:" + checkThreadPeriod);  
  130.     System.out.println("totalThread=" + totalThread);  
  131.     System.out.println("workThreadList.size()=" + workThreadList.size());  
  132.   }  
  133.   class WorkerThread extends Thread  
  134.   {  
  135.     boolean running = true;  
  136.     Work work;  
  137.     public void run()  
  138.     {  
  139.         while (running)  
  140.         {  
  141.           synchronized (o)  
  142.           {  
  143.             freeThreadCount++; //進來說明多了一個可用線程  
  144.           }  
  145.           synchronized (taskList)  
  146.           {  
  147.             while (taskList.size() == 0//當工作任務列表為空時等待  
  148.             {  
  149.                 try  
  150.                 {  
  151.                   taskList.wait();  
  152.                   if (!running) return;  
  153.                 }  
  154.                 catch (InterruptedException e)  
  155.                 {  
  156.                 }  
  157.             }  
  158.             synchronized (o)  
  159.             {  
  160.                 freeThreadCount--; //得到一個工作,可用線程減一  
  161.             }  
  162.             work = (Work) taskList.removeLast(); //從人物列裱中獲得一個任務  
  163.             if (work == nullreturn;  
  164.           }  
  165.           work.doWork();  
  166.         }  
  167.     }  
  168.   }  
  169. }  

CheckThreadTask.java

[java] view plaincopy
  1. import java.util.TimerTask;  
  2. public class CheckThreadTask extends TimerTask  
  3. {  
  4.   private static boolean isRunning = false;  
  5.   private ThreadPool pool;  
  6.   public CheckThreadTask(ThreadPool pool)  
  7.   {  
  8.     this.pool = pool;  
  9.   }  
  10.   public void run()  
  11.   {  
  12.     if (!isRunning)  
  13.     {  
  14.         isRunning = true;  
  15.         pool.checkAllThreads();  
  16.         isRunning = false;  
  17.     }  
  18.   }  
  19. }  

Work.java

[java] view plaincopy
  1. public interface Work  
  2. {  
  3.   public abstract void doWork();  
  4. }  

UtilProperties.java

[java] view plaincopy
  1. import java.io.File;  
  2. import java.io.FileInputStream;  
  3. import java.io.FileNotFoundException;  
  4. import java.io.FileOutputStream;  
  5. import java.io.IOException;  
  6. import java.util.Properties;  
  7. public class UtilProperties  
  8. {  
  9.   //  
  10.   private String fileName = System.getProperty("user.dir")  
  11.         + "/base/config.properties";  
  12.   private Properties prop;  
  13.   private FileInputStream in;  
  14.   private FileOutputStream out;  
  15.   /** *//** 
  16.     *  
  17.     * @param fileName 
  18.     */  
  19.   public UtilProperties(String filePath)  
  20.   {      
  21.       this.fileName = System.getProperty("user.dir")+filePath;  
  22.       getFile();  
  23.   }  
  24.   public UtilProperties()  
  25.   {  
  26.       getFile();  
  27.   }  
  28.    
  29.   /** *//** 
  30.     * 
  31.     */  
  32.   private void getFile()  
  33.   {  
  34.       File file = new File(this.fileName);  
  35.       try  
  36.       {  
  37.         in = new FileInputStream(file);  
  38.         prop = new Properties();  
  39.         //  
  40.         prop.load(in);  
  41.         in.close();  
  42.       }  
  43.       catch (FileNotFoundException e)  
  44.       {  
  45.         System.err.println("配置文件config.properties找不到!!");  
  46.       }  
  47.       catch (IOException e)  
  48.       {  
  49.         System.err.println("讀取配置文件config.properties錯誤!!");  
  50.       }      
  51.   }  
  52.   /** *//** 
  53.     * 列出所有配置文件內容 
  54.     */  
  55.   public void list()  
  56.   {  
  57.       prop.list(System.out);  
  58.   }  
  59.   /** *//** 
  60.     *  
  61.     * 
  62.     * @param itemName 
  63.     *         String 
  64.     * @return String 
  65.     */  
  66.   public String getValue(String itemName)  
  67.   {  
  68.       return prop.getProperty(itemName);  
  69.   }  
  70.   /** *//** 
  71.     *  
  72.     * 
  73.     * @param itemName 
  74.     *         String 
  75.     * @param value 
  76.     *         String 
  77.     */  
  78.   public void setValue(String itemName, String value)  
  79.   {  
  80.       prop.setProperty(itemName, value);  
  81.   }  
  82.   /** *//** 
  83.   *  
  84.   * 
  85.   * @param fileName 
  86.   *         String 
  87.   * @param description 
  88.   *         String 
  89.   * @throws Exception 
  90.   */  
  91.   public void saveFile()  
  92.   {  
  93.     try  
  94.     {  
  95.         File f = new File(this.fileName);  
  96.         out = new FileOutputStream(f);  
  97.         prop.store(out, "");  
  98.         out.close();  
  99.     }  
  100.     catch (FileNotFoundException e)  
  101.     {  
  102.         e.printStackTrace();  
  103.     }  
  104.     catch (IOException e)  
  105.     {  
  106.         System.err.println("配置文件config.properties寫入錯誤!!");  
  107.     }  
  108.   }  
  109.   /** *//** 
  110.   *  
  111.   * 
  112.   * @param value 
  113.   *         String 
  114.   */  
  115.   public void deleteValue(String value)  
  116.   {  
  117.     prop.remove(value);  
  118.   }  
  119.    
  120.   public void changeFile(String filePath)  
  121.   {  
  122.     this.fileName = System.getProperty("user.dir")+filePath;  
  123.     getFile();  
  124.   }  
  125.    
  126.   public static void main(String[] args)  
  127.   {  
  128.     UtilProperties up = new UtilProperties();  
  129.     up.list();  
  130. //    up.changeFile("/logs/config.properties");  
  131. //    up.list();  
  132.     System.out.println("/n"+up.getValue("tmpSavePath"));  
  133.   }  
  134. }   

0 0