多线程打印

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