多线程运行时有待处理线程?试试看下面介绍的这个批量线程同步方法吧。
在一批线程处理程序中,有时必须等到所有线程全部运行完后,才能进行下一步任务处理, 可以采用如下方法解决,创建一个锁对象 ,该锁对象提供一个当前线程等待其他线程的方法。见代码:
/** * * 此类主要用来处理线程的同步屏蔽模型,比如,一批线程运行,必须在最后一个线程运行 * 完后,才能进行下一步的操作,那么就可以创建一个锁对象,锁对象提供一个线程等待其他线程 * 的方法,如果当前线程运行时,还有未运行的线程,则此线程wait,否则,此线程唤醒其他阻塞的 * 线程,进而最终完成线程的运行 * */ public class LockObject { private int totalThread = 0; private int currentThread = 0; public LockObject(int totalThread) { this.totalThread = totalThread; this.currentThread = 1; } 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 = 1; 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 等待其他线程结束,即当前运行线程数与线程总数的比较
如果运行线程数小于线程总数,则当前运行线程数+1 后,当前线程进入等待状态,否则,唤醒其他等待线程。
见测试程序
public class MyThread extends Thread { public static LockObject lo = new LockObject(1000); 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 = 1; i <= 1000; i++) { Thread thread = new MyThread("第" + i + "个线程"); thread.setPriority(NORM_PRIORITY); thread.start(); } } } |
以上就介绍了批量线程同步的实现。