码迷,mamicode.com
首页 > 编程语言 > 详细

线程按照顺序打印

时间:2019-01-06 18:01:43      阅读:244      评论:0      收藏:0      [点我收藏+]

标签:public   oid   color   private   com   star   start   rgs   thread   

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


 

线程按照顺序打印

标签:public   oid   color   private   com   star   start   rgs   thread   

原文地址:https://www.cnblogs.com/startSeven/p/10229158.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!