zoukankan      html  css  js  c++  java
  • 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();    
                }    
            }    
        }    
    }    
  • 相关阅读:
    POJ_1698_Alice's Chance
    透过比特币看移动互联网创业产品立项的关键要素
    localhost与127.0.0.1的区别
    web service初探
    Oracle导出DMP文件的两种方法
    html大小写问题
    浏览器端数据存储
    CSS滚动条样式设置
    浅谈forword和sendRedirect
    Poi对excel的基本操作
  • 原文地址:https://www.cnblogs.com/mengyuxin/p/5358980.html
Copyright © 2011-2022 走看看