码迷,mamicode.com
首页 > 编程语言 > 详细

多线程打印

时间:2018-10-26 19:35:34      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:nts   over   pool   ati   not   shutdown   str   ring   new t   

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();
                }
            }
        }
    }
}

  

多线程打印

标签:nts   over   pool   ati   not   shutdown   str   ring   new t   

原文地址:https://www.cnblogs.com/LinsenLi/p/9857765.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!