首页 > 编程语言 > 详细

多线程打印

时间:2018-10-26 18:40:02      阅读:167      评论:0      收藏:0      [点我收藏+]
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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!