java实现多线程

package com.my.lianxi;

import java.util.ArrayList;
import java.util.List;

public class ThreadTest {    
    
    public static void main(String[] args) throws InterruptedException {    
        new Monitor().start();   
        
        new MyThread().launch();    
    }    
    
    
    
}    
    
class MyThread extends Thread {    
    //被争抢资源    
    public static Integer i = 0;    
    //线程容器    
    public static List<MyThread> list = new ArrayList<MyThread>();    
    //启动50个线程    
    public void launch() {    
        for (int i = 0; i < 50; i++) {    
            MyThread temThread = new MyThread();    
            list.add(temThread);    
            temThread.start();    
        }    
    }    
    
    @Override    
    public void run() {    
           
            try {    
                //增大争抢强度    
                Thread.sleep(2);    
            } catch (InterruptedException e) {    
                e.printStackTrace();    
            }    
            synchronized (MyThread.i) {   
                //主要的任务    
                MyThread.i++;    
            }    
    }    
}    
    
class Monitor extends Thread {    
    
    public int n = 0;    
    
    @Override    
    public void run() {    
        while (true) {    
            try {    
                //心跳1秒    
                sleep(1000);    
            } catch (InterruptedException e) {    
                e.printStackTrace();    
            }    
    
            //判断线程是否结束    
            boolean isOver = true;    
            for (MyThread thread : MyThread.list) {    
                // 如果有一个活着就没有结束    
                if (thread.isAlive()) {    
                    isOver = false;    
                }    
            }    
            //输出格式化    
            if (n % 10 == 0 && n != 0) {    
                System.out.println();    
            }    
            //结果输出    
            if (isOver) {    
            System.out.print(n++ + "-" + MyThread.i + "; ");    
                synchronized (MyThread.i) {    
                    MyThread.i = 0;    
                }  
                MyThread.list = new ArrayList<MyThread>();  
                new MyThread().launch();    
            }    
        }    
    }    
}    
原文地址:https://www.cnblogs.com/mengyuxin/p/5358980.html