主线程等待次线程执

来源:互联网 发布:907和140数据对比 编辑:程序博客网 时间:2024/06/08 17:33

一、

package com.shine.bill;

public class MyCountDown {

    private int count;

    public MyCountDown(int count) {
        this.count = count;
    }

    public synchronized void countDown() {
        count--;
    }

    public synchronized boolean hasNext() {
        return (count > 0);
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

}

二、

package com.shine.bill;

public class ImportThread extends Thread {

    private MyCountDown c;

    public ImportThread(MyCountDown c) {
        this.c = c;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "开始...");// 打印开始标记
        // Do something
        System.out.println(Thread.currentThread().getName() + "结束. 还有"
                + c.getCount() + " 个线程");// 打印结束标记

      c.countDown();// 计时器减1
    }

}

三、

package com.shine.bill;

public class Test2 {

    /**
     * @param args
     */
    public static void main(String[] args) {

        System.out.println(Thread.currentThread().getName() + "开始");// 打印开始标记
        int threadNum = 100;
        MyCountDown c = new MyCountDown(threadNum);// 初始化countDown
        for (int ii = 0; ii < threadNum; ii++) {// 开threadNum个线程
            Thread t = new ImportThread(c);
            t.start();
        }
        while (true) {// 等待所有子线程执行完
            if (!c.hasNext())
                break;
        }
        System.out.println(Thread.currentThread().getName() + "结束.");// 打印结束标
    }

}

四、分机部署

    public static void main(String[] args) {
        
        Long marchineNum = 3L;
        Long totalCount=10L;
        for (int i = 1; i <= marchineNum; i++) {
            // 从第几条记录开始
            long startIndex = (i - 1) *(totalCount/marchineNum);
            long endIndex=0;
            // 从第几条记录结束
            if(i==marchineNum)
            {
                endIndex =10L-1;
            }else{
                endIndex = startIndex + (totalCount/marchineNum)-1;
            }
            
           System.out.println("区间:"+startIndex+"-"+endIndex);
        }
        
    }

0 0
原创粉丝点击