zoukankan      html  css  js  c++  java
  • 多线程打印

    public class Main {
        public static void main(String[] args){
            ExecutorService pool = Executors.newFixedThreadPool(100);
            TestThread t = new TestThread();
            for(int i = 0;i<100; i++){
                pool.execute(t);
            }
            pool.shutdown();
        }
    }
    
    class TestThread implements Runnable {
        int i = 1;
        @Override
        public void run() {
            synchronized (this) {
                System.out.println(i);
                i++;
            }
        }
    }
    

      

    public class Main2 {
        public static void main(String[] args){
            TestThread2 t = new TestThread2();
            ExecutorService pool = Executors.newFixedThreadPool(2);
            for(int i=0; i<2; i++){
                pool.execute(t);
            }
            pool.shutdown();
        }
    }
    
    
    class TestThread2 implements Runnable {
        int i = 1;
        @Override
        public void run() {
            while (!Thread.currentThread().isInterrupted()) {
                synchronized (this) {
                    notify();
                    if (i <= 100) {
                        System.out.println(Thread.currentThread().getName() + ":" + i);
                        i++;
                        try {
                            wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    else{
                        Thread.currentThread().interrupt();
                    }
                }
            }
        }
    }
    

      

  • 相关阅读:
    农场灌溉问题(回溯)
    六数码问题(广搜_队列)
    求图像周长(回溯)
    六数码问题(回溯)
    花生米(四)
    活动安排(贪心算法)
    自我介绍
    三位老师
    培训期间
    工作十个月感触
  • 原文地址:https://www.cnblogs.com/LinsenLi/p/9857765.html
Copyright © 2011-2022 走看看