暂停Java中的线程 [英] pausing threads in java

查看:54
本文介绍了暂停Java中的线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I was wondering if someone coule help me on how to implement a thread which runs infinitely in the background until the user presses p at which point it pauses the other threads and upon pressing r resumes other threads. This is some of the code

一些主要对象

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

播放器对象是要暂停的线程

The player object which are the threads to be paused

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

}

玩家将玩游戏",在游戏中他们从数组中绘制对象并丢弃对象,但是用户应该能够在游戏过程中的任何时候暂停并恢复程序.我只是不太了解如何使用事件和列表器来解决这个问题.

The players will be 'playing a game' where they draw and discard objects from arrays, but the user should be able to pause and resume the programm at any point during the game. i just dont quite understand how to go about that, using events and listners.

我们将不胜感激.谢谢.

Help would be appreciated. Thank you.

推荐答案

Thread本身没有机制.但是,您可以轻松地将此功能添加到自己的过程中.您将需要设置一些标志并进行检查,然后最好是设置一个等待/通知方案.这是一个简单的演示:

Thread has no mechanism for this on its own. You can, however, easily add this functionality in to your own process. You'll have some flag to set and check and then probably the best is to have a wait/notify scheme. Here's a simple demonstration:

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,请查看

For taking user input from the keyboard, there's not really a convenient way to do that in Java. If you want to take straight keystrokes you need a GUI component for them to happen in. If you do plan on implementing a GUI take a look at the key bindings tutorial.

这篇关于暂停Java中的线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆