新聞中心
多線程運(yùn)行時(shí)有待處理線程?試試看下面介紹的這個(gè)批量線程同步方法吧。

我們一直強(qiáng)調(diào)網(wǎng)站設(shè)計(jì)制作、成都網(wǎng)站制作對(duì)于企業(yè)的重要性,如果您也覺得重要,那么就需要我們慎重對(duì)待,選擇一個(gè)安全靠譜的網(wǎng)站建設(shè)公司,企業(yè)網(wǎng)站我們建議是要么不做,要么就做好,讓網(wǎng)站能真正成為企業(yè)發(fā)展過程中的有力推手。專業(yè)網(wǎng)站設(shè)計(jì)公司不一定是大公司,成都創(chuàng)新互聯(lián)作為專業(yè)的網(wǎng)絡(luò)公司選擇我們就是放心。
在一批線程處理程序中,有時(shí)必須等到所有線程全部運(yùn)行完后,才能進(jìn)行下一步任務(wù)處理, 可以采用如下方法解決,創(chuàng)建一個(gè)鎖對(duì)象 ,該鎖對(duì)象提供一個(gè)當(dāng)前線程等待其他線程的方法。見代碼:
- /**
- *
- * 此類主要用來處理線程的同步屏蔽模型,比如,一批線程運(yùn)行,必須在最后一個(gè)線程運(yùn)行
- * 完后,才能進(jìn)行下一步的操作,那么就可以創(chuàng)建一個(gè)鎖對(duì)象,鎖對(duì)象提供一個(gè)線程等待其他線程
- * 的方法,如果當(dāng)前線程運(yùn)行時(shí),還有未運(yùn)行的線程,則此線程wait,否則,此線程喚醒其他阻塞的
- * 線程,進(jìn)而最終完成線程的運(yùn)行
- * */
- 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;
- }
- }
批量線程同步機(jī)制介紹
此對(duì)象提供 二個(gè)私有變量,totalThread 的初始值為所運(yùn)行的線程的總數(shù),currentThread 為當(dāng)前正在運(yùn)行的線程數(shù)。
線程運(yùn)行時(shí)處理完自己的任務(wù)后調(diào)用方法waitForOtherThread 等待其他線程結(jié)束,即當(dāng)前運(yùn)行線程數(shù)與線程總數(shù)的比較
如果運(yùn)行線程數(shù)小于線程總數(shù),則當(dāng)前運(yùn)行線程數(shù)+1 后,當(dāng)前線程進(jìn)入等待狀態(tài),否則,喚醒其他等待線程。
見測(cè)試程序
- 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() + " ----開始運(yùn)行");
- lo.waitForOtherThread();
- System.out.println(Thread.currentThread().getName() + " ----結(jié)束運(yùn)行");
- }
- public static void main(String[] args) {
- for (int i = 1; i <= 1000; i++) {
- Thread thread = new MyThread("第" + i + "個(gè)線程");
- thread.setPriority(NORM_PRIORITY);
- thread.start();
- }
- }
- }
以上就介紹了批量線程同步的實(shí)現(xiàn)。
【編輯推薦】
- C#線程同步詳細(xì)分析
- 運(yùn)用C#數(shù)據(jù)提供者
- C#允許運(yùn)算符重載剖析
- Java和C#頂層聲明概述
- C#完全限定名簡(jiǎn)單分析
網(wǎng)站題目:多線程的批量線程同步解決方案
鏈接URL:http://m.5511xx.com/article/cohocpc.html


咨詢
建站咨詢
