简体   繁体   中英

Two threads accessing the same char matrix alternatively

I'm trying to make a "X and O" game using threads. I use a char matrix[3][3] for my game table and I want the first thread to put "X" and after that to show the matrix and then the second threat to pun "O" and so on. How can I do this using threads?

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++;
    }
}

}

And this is my main

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();

}

}

This is my code so far but after the first x and y coord it stops.

The problem is here, after the first 'x,y' both threads are waiting for the 'ins' Semaphore, and no one cares about the 'outs'.

You can fix it by remove 'outs' and use only 'ins'. Here you should double check, that how acquire is implemented. Does it grantee a queue or can a thread acquire it twice rarely?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM