JUC 1234线程

2017-10-11  本文已影响47人  刘尔泽
image.png

题目如图所示

package com.example;

import java.util.concurrent.CyclicBarrier;

/**
 * Created by Java 群 坦克
 */

public class MyClass {

    public static void main(String[] args) {
        final int N = 4;
        final CyclicBarrier barrier = new CyclicBarrier(N);
        final StringBuilder[] buffers = new StringBuilder[N];
        Thread[] threads = new Thread[N];

        for (int i = 0; i < N; i++) {
            buffers[i] = new StringBuilder();
            final int id = i;
            threads[i] = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        for (int x = id; ; x = (x + N - 1) % N) {
                            barrier.await();
                            buffers[x].append(id + 1);
                        }
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
            });
            threads[i].start();
        }
        ////////////////////////////////////////////////////////
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        for (StringBuilder buffer : buffers) {
            System.out.println(buffer);
        }
        System.exit(0);
    }
}

result :


image.png

我当时 想的

刘尔泽:这个题,我想的是四个线程维护一个信号量,然后按时间片每次试图往上一个文件里写入

image.png

还有再看看的

后来 他又写了一个版本

image.png
坦克 2017/11/22 18:22:49
    static final int N = 4;
    static final CyclicBarrier barrier = new CyclicBarrier(N);
    static final StringBuilder[] mockFiles = new StringBuilder[N];
    static {
        for (int i = 0; i < mockFiles.length; mockFiles[i++] = new StringBuilder());
    }
    static boolean running = true;

    public static void main(String[] args) throws Exception {
        for (int i = 0; i < N; i++) {
            new Worker(i).start();
        }
        Thread.sleep(500);
        running = false;
        for (StringBuilder mockFile : mockFiles) {
            System.out.println(mockFile);
        }
    }

    static class Worker extends Thread {
        final int index;
        public Worker(int index) {
            this.index = index;
        }
        public void run() {
            try {
                for (int d = index + 1, pos = index; running; pos = (pos + N - 1) % N) {
                    barrier.await();
                    StringBuilder mockFile = mockFiles[pos];
                    mockFile.append(d);
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

上一篇 下一篇

猜你喜欢

热点阅读