1. 程式人生 > >執行緒按照順序列印

執行緒按照順序列印

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