多线程打印
Posted linsenli
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多线程打印相关的知识,希望对你有一定的参考价值。
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(); } } } } }
以上是关于多线程打印的主要内容,如果未能解决你的问题,请参考以下文章