LeetCode Java 相关题目

LeetCode Java 相关题目

交替打印

  • 思路分析:类的核心状态是 arr、线程数量、数组下标 cursor、当前线程 id(循环更新)。
public class 交替打印数组 {

    public static void main(String[] args) {

        int[] arr= new int[]{1,2,3,4,5,6,7,8,9};

        int m = 3;

        Printer printer = new Printer(arr, m);

        for(int i = 0;i<3;i++){

            final int fi = i;

            new Thread(new Runnable() {

                @Override

                public void run() {

                    printer.prient(fi);

                }

            }).start();

        }

    }

}

  

class Printer {

    int[] arr;

    int threadCounts;

    int cursor;

    int currentThreadId;

  

    Printer(int[] arr, int count) {

        this.arr = arr;

        this.threadCounts = count;

        this.cursor = 0;

        this.currentThreadId = 0;

    }

  

    public void prient(int threadId) {

        synchronized (this) {

            while (true) {

                // 不是当前线程 阻塞

                while (true) {

                    if (cursor>=arr.length) {

                        break;

                    }

                    if (threadId == currentThreadId) {

                        break;

                    }

                    try {

                        this.wait();

                    } catch (InterruptedException e) {

                        // TODO Auto-generated catch block

                        e.printStackTrace();

                    }

                }

                if (cursor>=arr.length) {

                    this.notifyAll();

                    break;

                }

                // 打印, 修改cursor, 和 current id

  

                System.out.println("ThreadId: "+threadId+'\t'+arr[cursor]);

  

                cursor++;

                currentThreadId = (currentThreadId + 1) % threadCounts;

  

                this.notifyAll();

  

            }

        }

  

    }

}