美文网首页
并发输出ABC

并发输出ABC

作者: 人失格 | 来源:发表于2017-01-09 19:43 被阅读58次

多线程顺序执行

问题是这样的:

有A,B,C三个线程, A线程输出A, B线程输出B, C线程输出C

要求, 同时启动三个线程, 按顺序输出ABC, 循环10次

这是一个多线程协同的问题, 本身多线程是没有执行顺序的, 顺序不一定。

package Current.prac1;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by finch on 2017/1/9.
 */
public class Task {
    private static Lock lock = new ReentrantLock();//通过JDK5中的锁来保证线程的访问的互斥
    private volatile static int state = 0;

    private static Task lock1 = new Task();

    static class ThreadA extends Thread {
        @Override
        public void run() {
            for (int i = 0; i < 10; ) {
                synchronized (lock1) {
                    if (state % 3 == 0) {
                        System.out.print("A");
                        state++;
                        i++;
                    }
                }
            }
        }
    }


    static class ThreadB extends Thread {
        @Override
        public void run() {
            for (int i = 0; i < 10; ) {
                //lock.lock();
                synchronized (lock1) {
                    if (state % 3 == 1) {
                        System.out.print("B");
                        state++;
                        i++;
                    }
                }
            }
        }
    }

    static class ThreadC extends Thread {
        @Override
        public void run() {
            for (int i = 0; i < 10; ) {
                //lock.lock();

                synchronized (lock1) {
                    if (state % 3 == 2) {
                        System.out.print("C");
                        state++;
                        i++;
                    }
                }

                //lock.unlock();
            }
        }
    }

    public static void main(String[] args) {
        new ThreadA().start();
        new ThreadB().start();
        new ThreadC().start();
    }
}

相关文章

网友评论

      本文标题:并发输出ABC

      本文链接:https://www.haomeiwen.com/subject/ypmhbttx.html