一道Google面试题目:4个线程写4个文件

题目大意:

4个线程写4个文件,

A线程只能写A,B线程只能写B,C线程只能写C,D线程只能写D,

最后结果如下:

File1: ABCDABCD... 

File2: BCDABCDA... 

File3: CDABCDAB... 

File4: DABCDABC...


以下是我用java写的一个小demo,实现了这个功能.

下载链接 http://download.csdn.net/detail/ober2012/9423119

3个类:

LazyWriter 实现主要功能的线程类

WritersParty 程序入口

Table 数据类,用4个数组模拟4个文件

</pre><pre name="code" class="java">package com.example;

import java.util.List;
import java.util.Random;
import java.util.concurrent.BrokenBarrierException;

/**
 * Created by ober on 2016/1/29.
 */
public class LazyWriter extends Thread {
    private String words; //他能写的字
    private int sequence; //他的顺序
    private Table mTable; //数据类
    private int targetPaperIndex; //当前准备写的文件index

    private volatile boolean alive;

    private static final Random r = new Random();

    public LazyWriter(String words, int sequence, Table table) {
        this.words = words;
        this.mTable = table;
        this.sequence = sequence;
        targetPaperIndex = sequence;
        alive = true;
    }

    public void killSelf() {
        synchronized (this) {
            alive = false;
        }
    }

    @Override
    public void run() {
        WritersParty.START_COUNTER.countDown();
        while (alive) {
            try {
                writeOnPaper(findTargetPaper());
                lookAtNextTargetPaper();
                WritersParty.BARRIER.await();
            } catch (InterruptedException | BrokenBarrierException e) {
                e.printStackTrace();
            }
        }
        WritersParty.END_COUNTER.countDown();
    }

    private List<String> findTargetPaper() {
        return mTable.getPaper(targetPaperIndex);
    }

    private void writeOnPaper(List<String> paper) throws InterruptedException {
        sleep(getSleepTime());//模拟耗时操作
        paper.add(words);
        System.out.println("Writer" + sequence + " write "
                + words + " on paper" + (targetPaperIndex % 4));
    }

    private void lookAtNextTargetPaper() {
        targetPaperIndex += 3; // 写完这个文件之后,他将写的下个文件是排在他前面的一个
    }

    private static long getSleepTime() {
        return 100 + r.nextInt(500);
    }

}

package com.example;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by ober on 2016/1/29.
 */
public class Table {
    private List<String> paper0;
    private List<String> paper1;
    private List<String> paper2;
    private List<String> paper3;

    public Table() {
        paper0 = new ArrayList<>();
        paper1 = new ArrayList<>();
        paper2 = new ArrayList<>();
        paper3= new ArrayList<>();
    }

    public List<String> getPaper(int sequence) {
        int index = sequence % 4;
        if(index == 0) {
            return paper0;
        } else if(index == 1) {
            return paper1;
        } else if(index == 2) {
            return paper2;
        } else {
            return paper3;
        }
    }

    public void showOff() {
        System.out.println("paper0: " + paperToString(paper0));
        System.out.println("paper1: " + paperToString(paper1));
        System.out.println("paper2: " + paperToString(paper2));
        System.out.println("paper3: " + paperToString(paper3));
    }

    private static String paperToString(List<String> paper) {
        StringBuilder sb = new StringBuilder();
        for(String s : paper) {
            sb.append(s);
        }
        return sb.toString();
    }

package com.example;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;

/**
 * Created by ober on 2016/1/30.
 */
public class WritersParty {

    public static final CyclicBarrier BARRIER = new CyclicBarrier(4);

    public static final CountDownLatch START_COUNTER = new CountDownLatch(4);
    public static final CountDownLatch END_COUNTER = new CountDownLatch(4);


    public static void main(String[] args) throws InterruptedException {
        Table table = new Table();

        LazyWriter writerA = new LazyWriter("A", 0, table);
        LazyWriter writerB = new LazyWriter("B", 1, table);
        LazyWriter writerC = new LazyWriter("C", 2, table);
        LazyWriter writerD = new LazyWriter("D", 3, table);

        writerA.start();
        writerB.start();
        writerC.start();
        writerD.start();

        START_COUNTER.await();

        Thread.sleep(30000); //执行30s

        writerA.killSelf();
        writerB.killSelf();
        writerC.killSelf();
        writerD.killSelf();

        END_COUNTER.await();

        table.showOff();
    }
}



  • 5
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值