今天就跟大家聊聊有關(guān)使用java怎么實現(xiàn)一個多線程的交替打印,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。
notify+wait實現(xiàn)
import org.junit.Test; import java.util.concurrent.*; public class TestThreadLocal { Object o = new Object(); CountDownLatch c=new CountDownLatch(2); @Test public void vvvvvvvv() throws InterruptedException { Thread t1 = new Thread() { @Override public void run() { for (int i = 0; i < 26; i++) { synchronized (o) { System.out.print((char) (65 + i)); o.notify(); try { if(i<25)o.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } c.countDown(); } }; Thread t2 = new Thread() { @Override public void run() { for (int i = 0; i < 26; i++) { synchronized (o) { System.out.print(1 + i); o.notify(); try { if(i<25)o.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } c.countDown(); } }; t1.start(); t2.start(); //t1.join(); //t2.join(); c.await(); } }