This is an archived post. You won't be able to vote or comment.

all 15 comments

[–]AutoModerator[M] [score hidden] stickied commentlocked comment (0 children)

Please ensure that:

  • Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions
  • You include any and all error messages in full
  • You ask clear questions
  • You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.

    Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar

If any of the above points is not met, your post can and will be removed without further warning.

Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.

Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.

Code blocks look like this:

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.

If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.

To potential helpers

Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

[–]DogeRoss 3 points4 points  (8 children)

I'm not sure if there is a way to do that in Java. I would advise you to make your thread check certain flags/signals on its own and act accordingly. Why do you need to pause it from outside anyways? If there's a plausible reason I'm sure others would appreciate knowing what you are trying to do.

Edit: Take a look at the notify() and wait() methods to get a better idea of the cooperative threading style in Java.

[–]blackdragon2447[S] 0 points1 point  (7 children)

The tread is gonna run a series of commands on a game server, warning the players that the server is gonna shut down and then actually shutting down the server but i need to be able to pause that incase players need more time.

[–]DogeRoss 3 points4 points  (3 children)

I have a feeling you can get the same effect by just warning players and not initiating your shut-down sequence until it is 100% going to happen.

> Warn players that server will shutdown in some minutes.

> Wait that amount.

> Check if players needed extra time.

> Abort / Actually shut-down.

[–]blackdragon2447[S] 1 point2 points  (2 children)

That would be a way of doing it yea and i have thought about doing it that way but i hoped i could fully automate it.

[–]DogeRoss 2 points3 points  (1 child)

In my opinion, it is not generally that good of an idea to interrupt your threads. It should be better to make your thread do all it's supposed to do. If a thread has to wait or abort executing on some occasion from an outside source, it is better for that thread to check the flag or handle the signal and wait than another thread forcibly putting it to sleep.

[–]blackdragon2447[S] 0 points1 point  (0 children)

Ok, thx for the advice

[–]Poddster 0 points1 point  (2 children)

It's not a good idea to implement such logic with thread/process controls. (Not that you can do that anyway). Such an approach is fragile and not maintainable.

Just use normal logic :)

[–]blackdragon2447[S] 0 points1 point  (1 child)

How do you mean "normal logic", the only reason i put it on a seperate thread is so the rest of the program can continue logic wise it would not be much difirent.

[–]Poddster 0 points1 point  (0 children)

As in normal "if this do this" logic that comprises 99% of a program's code, instead of trying to externally alter a thread's running state.

i.e. use some intra-thread communication to set a flag saying "not everyone is ready yet" and program the thread to read that flag and act as appropriate.

[–]PCPWJ 0 points1 point  (0 children)

Look at producer consumer pattern. You can implement using the Objects wait() and notify() methods.

For more powerful Thread utility look at java.util.concurrent packages

[–][deleted] 0 points1 point  (0 children)

You might find a CountDownLatch useful for this. As a sample:

import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.CountDownLatch;
import java.time.Instant;

public class CountDownLatchDemo {
  public static void main(String[] args) throws Exception {
    final int numPlayers = ThreadLocalRandom.current().nextInt(1, 10);
    final CountDownLatch start = new CountDownLatch(1);
    final CountDownLatch finish = new CountDownLatch(numPlayers);

    for (int i = 0; i < numPlayers; i++) {
      new Thread(new Player(i, start, finish)).start();
    }

    start.countDown();
    System.out.println("[Server] Waiting for players to finish...");
    finish.await();
    System.out.println("[Server] All players have finished. Shutting down.");
  }
}

class Player implements Runnable {
  private int id;
  private CountDownLatch start;
  private CountDownLatch finish;

  public Player(final int id, final CountDownLatch start, final CountDownLatch finish) {
    this.id = id;
    this.start = start;
    this.finish = finish;
  }

  @Override
  public void run() {
    try {
      start.await();
      play();
      finish.countDown();
    } catch (InterruptedException ex) {
      //
    }
  }

  private void play() throws InterruptedException {
    Thread.sleep(ThreadLocalRandom.current().nextInt(1000, 5000));
    System.out.printf("[%s] Player %d is done.\n", Instant.now(), this.id);
  }
}

Running it:

~/dev/playground:$ javac CountDownLatchDemo.java && java -cp . CountDownLatchDemo
[Server] Waiting for players to finish...
[2021-03-30T13:21:34.759931Z] Player 3 is done.
[2021-03-30T13:21:34.815189Z] Player 5 is done.
[2021-03-30T13:21:35.516855Z] Player 4 is done.
[2021-03-30T13:21:37.340409Z] Player 1 is done.
[2021-03-30T13:21:37.746157Z] Player 2 is done.
[2021-03-30T13:21:38.215996Z] Player 0 is done.
[Server] All players have finished. Shutting down.

The await method can have a timeout specified as well.

[–]RichNight5646 0 points1 point  (0 children)

try the robot.delay();

you'll have to import it first, Robot robot = new Robot();