多线程的批量线程同步解决方案

如题所述

第1个回答  2022-10-31

  多线程运行时有待处理线程?试试看下面介绍的这个批量线程同步方法吧

  在一批线程处理程序中 有时必须等到所有线程全部运行完后 才能进行下一步任务处理 可以采用如下方法解决 创建一个锁对象 该锁对象提供一个当前线程等待其他线程的方法 见代码

   /**

   *

   * 此类主要用来处理线程的同步屏蔽模型 比如 一批线程运行 必须在最后一个线程运行

   * 完后 才能进行下一步的操作 那么就可以创建一个锁对象 锁对象提供一个线程等待其他线程

   * 的方法 如果当前线程运行时 还有未运行的线程 则此线程wait 否则 此线程唤醒其他阻塞的

   * 线程 进而最终完成线程的运行

   * */

   public class LockObject {

  

   private int totalThread = ;

   private int currentThread = ;

  

   public LockObject(int totalThread) {

     this totalThread = totalThread;

     this currentThread = ;

   }

  

   public synchronized void waitForOtherThread() {

     if (this currentThread < this totalThread) {

      this currentThread++;

      try {

       this wait();

      } catch (InterruptedException e) {

       // TODO Auto generated catch block

       e printStackTrace();

      }

     } else {

      this currentThread = ;

      notifyAll();

     }

   }

  

   public int getTotalThread() {

     return totalThread;

   }

  

   public void setTotalThread(int totalThread) {

     this totalThread = totalThread;

   }

  

   public int getCurrentThread() {

     return currentThread;

   }

  

   public void setCurrentThread(int currentThread) {

     this currentThread = currentThread;

   }

   }

  

   批量线程同步机制介绍

  此对象提供 二个私有变量 totalThread 的初始值为所运行的线程的总数 currentThread 为当前正在运行的线程数

  线程运行时处理完自己的任务后调用方法waitForOtherThread 等待其他线程结束 即当前运行线程数与线程总数的比较

  如果运行线程数小于线程总数 则当前运行线程数+ 后 当前线程进入等待状态 否则 唤醒其他等待线程

  见测试程序

   public class MyThread extends Thread {

   public static LockObject lo = new LockObject( );

  

   public MyThread(String threadName) {

     super(threadName);

   }

  

   public void run() {

      System out println(Thread currentThread() getName() + 开始运行 );

      lo waitForOtherThread();

      System out println(Thread currentThread() getName() + 结束运行 );

   }

  

   public static void main(String[] args) {

     for (int i = ; i <= ; i++) {

      Thread thread = new MyThread( 第 + i + 个线程 );

      thread setPriority(NORM_PRIORITY);

      thread start();

     }

   }

  

   }

lishixinzhi/Article/program/Java/gj/201311/27516

相似回答