簡體   English   中英

兩個線程交替訪問同一字符矩陣

[英]Two threads accessing the same char matrix alternatively

我正在嘗試使用線程制作“ X and O”游戲。 我在游戲桌中使用了char矩陣[3] [3],我希望第一個線程放入“ X”,然后在其中顯示矩陣,然后讓第二個威脅打“ O”,依此類推。 我該如何使用線程?

public class ThreadExample implements Runnable {
private char[][] array;
private Semaphore ins, outs;
private int counter;

ThreadExample(Semaphore ins, Semaphore outs) {
    this.ins = ins;
    this.outs = outs;
    this.counter = 0;
    this.array = new char[3][3];
}

@Override
public void run() {
    for (int i = 0; i < 9; i++) {
        try {
            ins.acquire();
        } catch (InterruptedException e) {

            e.printStackTrace();
        } // wait for permission to run
        print();
        playTurn();
        outs.release(); // allow another thread to run
    }
}

private void print() {
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            System.out.print(array[i][j] + " ");
        }
        System.out.println();
    }
}

private synchronized void playTurn() {
    Scanner sc = new Scanner(System.in);
    int x;
    int y;
    System.out.println("enter the x coord: ");
    x = sc.nextInt();
    System.out.println("enter the y coord: ");
    y = sc.nextInt();
    // sc.close();
    if (counter % 2 == 0) {
        array[x][y] = 'X';
        counter++;
    } else {
        array[x][y] = 'O';
        counter++;
    }
}

}

這是我的主要

public class Main {
public static void main(String[] args) {
    Semaphore a = new Semaphore(1);
    Semaphore b = new Semaphore(0);

    ThreadExample th1 = new ThreadExample(a, b);

    Thread tr1 = new Thread(th1);
    Thread tr2 = new Thread(th1);
    tr1.start();
    tr2.start();

}

}

到目前為止,這是我的代碼,但是在第一個x和y坐標之后,它停止了。

問題出在這里,在第一個'x,y'之后,兩個線程都在等待'in'信號量,而沒有人在乎'out'。

您可以通過刪除“輸出”來解決它,而僅使用“輸入”。 在這里,您應該仔細檢查,如何實現獲取。 它授予隊列還是線程很少能兩次獲取它?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM