线程按照顺序打印
Posted startseven
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了线程按照顺序打印相关的知识,希望对你有一定的参考价值。
package com.cn.test.thread; /** *abc三个线程顺序打印十次 */ public class TestSortedThread extends Thread{ static int threadFlag = 1; public TestSortedThread(String string) { super(string); } @Override public void run() { for (int i=0; i<10; i++) { sortThread(); } } // 线程排序 private void sortThread() { while (threadFlag == 1) { if (Thread.currentThread().getName() == "thread-a") { System.out.println("A"); threadFlag ++; } else { Thread.currentThread().yield(); } } while (threadFlag == 2) { if (Thread.currentThread().getName() == "thread-b") { System.out.println("B"); threadFlag ++; } else { Thread.currentThread().yield(); } } while (threadFlag == 3) { if (Thread.currentThread().getName() == "thread-c") { System.out.println("C"); threadFlag = threadFlag -2 ; } else { Thread.currentThread().yield(); } } } public static void main(String[] args) { TestSortedThread threadA = new TestSortedThread("thread-a"); TestSortedThread threadB = new TestSortedThread("thread-b"); TestSortedThread threadC = new TestSortedThread("thread-c"); threadA.start(); threadB.start(); threadC.start(); }
以上是关于线程按照顺序打印的主要内容,如果未能解决你的问题,请参考以下文章
使用A线程打印1-52,B线程打印A-Z,要求按照12A34B56C....5152Z的顺序进行交替打印
JUC并发编程 共享模式之工具 JUC CountdownLatch(倒计时锁) -- CountdownLatch应用(等待多个线程准备完毕( 可以覆盖上次的打印内)等待多个远程调用结束)(代码片段