多线程---批量线程同步模型

本文介绍了一种线程同步方法,通过创建LockObject类实现多个线程间的同步控制。当所有线程完成任务后,程序才进入下一步。适用于需要确保所有线程完成任务场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

/**
 * 
 * 此类主要用来处理线程的同步屏蔽模型,比如,一批线程运行,必须在最后一个线程运行
 * 完后,才能进行下一步的操作,那么就可以创建一个锁对象,锁对象提供一个线程等待其他线程
 * 的方法,如果当前线程运行时,还有未运行的线程,则此线程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();
		}
	}

}

 。。。。。。。。初次发帖,如有不妥,欢迎拍砖!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值