Обновите столбец для быстрого анализа

У вас может быть общее логическое значение, в котором ваш поток и основной общий ресурс синхронизированы.

Таймер может быть следующим:

class timer extends Thread{//thread
private Object lock = new Object(); // a lock used by both your thread and main to access stop boolean
private boolean stop = false;
public void setStop() // your thread calls this method in order to set stop
{
   synchronized(lock) {
   stop = true;
   }
}

public boolean getStop() // main calls this to see if thread told main to stop.
{
   boolean _stop;
   synchronized(lock) {
   _stop = stop;
   }
   return _stop;
}
public void run(){
    for(int i=10;i>=0;i--){
        System.out.print(i+" ");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        setStop();
    }
}
}

Ваш основной может быть следующим образом :

timer t=new timer();
            t.start();
            while (!t.getStop()) {// calls getStop to see if other thread told main to stop
                System.out.print("Guess a word on the board! ");
                if(test.CheckGame(scan.next())==true){
                    System.out.print("Good job! ");
                }
                else    
                    System.out.print("Guess again! ");
            }
            t.join(); // to make sure main terminates after the termination of other thread
0
задан 7 March 2019 в 11:02
поделиться