在java中暂停线程

时间:2013-12-07 16:40:49

标签: java multithreading

我想知道是否有人帮助我如何实现一个在后台无限运行的线程,直到用户按下p,此时它会暂停其他线程并按下r恢复其他线程。这是一些代码

一些主要对象

public class CardGame
{
   static Player[] players;
   static int handSize;
   static Queue<Card>[] playingDeckArray;


public static void main(String[] args){
        Scanner reader = new Scanner(System.in);

        System.out.println( "\nHello, how many players would you like" );
        int playersNum = Integer.parseInt(Checks.userInputCheck( "\\d" ));
        System.out.println( "\nHow many cards should each player begin with" );
        int handSize = Integer.parseInt(Checks.userInputCheck( "\\d" ));
        System.out.println( "\nWhich strategy would you like to use 1 or 2" );
        int strategy = Integer.parseInt(Checks.userInputCheck( "[12]$" ));

        Logger.createDeck( playersNum, handSize );

        makePlayers( playersNum, handSize, strategy );

        makePlayingDecks( playersNum );

        dealInitialHand( playersNum, players, handSize );

        makePlayerOutputs();

        for ( int i = 0; i < players.length; i++){
           logInitialHand(players[i]);
        }

        CardGame cG = new CardGame();
        cG.startPauseThread();

        for ( int i = 0; i < players.length; i++){
            new Thread(players[i]).start();
        }
   }

   public void startPauseThread(){
   Thread add = new Thread( pauseInputThread );
   add.start();
}


Thread pauseInputThread = new Thread(){
       public void run(){ 
         int i = 0;
         for(;;){
             System.out.println("i'm still here" );
             Scanner reader = new Scanner(System.in);
             String result = Checks.userInputCheck( "[pPrR]$" );
             i++;
             System.out.println(i);
            }
       }
};
}

作为要暂停的线程的播放器对象

public class Player implements Runnable
{
    Card[] hand;
    String playerName;
    int strategyChosen;

    public void run(){
        System.out.println( "les do dis" );
    }

    private Player(){
    }

    public Player( int strategy, int cardsInHand, int playerNumber ){
        hand = new Card[cardsInHand];
        strategyChosen = strategy;
        playerName = "Player " + playerNumber;
    }

    public String getPlayerName(){
        return playerName;
    }

    public void fillHand(){
       for ( int i = 0; i < hand.length; i++){
            hand[i] = new Card(0);
       }
    }

    public void setHand( int value, int index ){
        hand[index].setCardValue( value );
    }

    public void seeHand(){
        for ( int i = 0; i < hand.length; i++){
            System.out.println( hand[i].getCardValue() );
        }
    }

    public String getHand(){
        String result = "";
        for ( int i = 0; i < hand.length; i++ ){
            result = result +  hand[i].getCardValue() + " \n" ;
        } 
        return result;
    }

    public int getHandValue( Card card ){
        return card.getCardValue();
    }

}

玩家将“玩游戏”,他们从阵列中绘制和丢弃对象,但用户应该能够在游戏过程中的任何时刻暂停和恢复程序。我只是不太明白如何去做,使用事件和列表。

帮助将不胜感激。谢谢。

2 个答案:

答案 0 :(得分:5)

Thread本身没有相应的机制。但是,您可以轻松地将此功能添加到您自己的流程中。你将有一些标志来设置和检查,然后最好的是有一个等待/通知方案。这是一个简单的演示:

abstract class PausableTask implements Runnable {
    private volatile boolean paused;
    private final Object lock = new Object();

    void setPaused(boolean shouldPause) {
        synchronized (lock) {
            paused = shouldPause;
            if (!paused) {
                lock.notify();
            }
        }
    }

    boolean isPaused() { return paused; }

    @Override
    public void run() {

        for (;;) {                
            synchronized (lock) {
                while (paused) {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {}
                }
            }

            doTask();
        }
    }

    abstract void doTask();
}

class Counter {
    volatile long count;

    public static void main(String[] args) {
        final Counter counter = new Counter();

        PausableTask increment = new PausableTask() {
            @Override
            void doTask() {
                counter.count++;
            }
        };

        PausableTask decrement = new PausableTask() {
            @Override
            void doTask() {
                counter.count--;
            }
        };

        decrement.setPaused(true);
        PausableTask next = increment;

        Scanner in = new Scanner(System.in);
        long count = counter.count;

        new Thread(increment).start();
        new Thread(decrement).start();

        for (;;) {
            System.out.print(
                (next == increment ? "Counting up from " : "Counting down from ")
                + count + ". Enter 'exit' to abort or anything else to toggle: "
            );

            if (in.nextLine().equals("exit")) {
                System.exit(0);
            }

            if (increment.isPaused()) {
                next = increment;
                decrement.setPaused(true);
            } else {
                next = decrement;
                increment.setPaused(true);
            }

            count = counter.count;
            next.setPaused(false);
        }
    }
}

为了从键盘获取用户输入,在Java中实际上没有一种方便的方法。如果你想直接击键,你需要一个GUI组件让它们发生。如果你计划实现GUI,请看看key bindings tutorial

答案 1 :(得分:1)

仅通过调用某个预定义方法暂停一个线程是不可能的,也不可能杀死一个线程。您唯一能做的就是自己实现这种行为。这意味着你会做这样的事情:

public class MyThread extends Thread {
    private volatile boolean running = true;
    private volatile boolean paused  = false;

    public void kill() {
        this.running = false;
    }

    public void setPaused(boolean paused) {
        this.paused = paused;
    }

    @Override
    public void run() {
        while (running) {
            if (!paused) {
                // do another step
            }
        }
    }
}

然而,我可能没有正确理解你的问题。给我一个反馈,这样我最终可以更新我的答案。