0

I am new to Threads. I have a GUI with a button that starts a thread executing core operations; I've got another button which should pause the main thread when pressed.

Is it possible to resume the main thread from where it stopped? The core of the question is from where the thread resumes, so it is not a duplicate question.

Thank you.

sirdan
  • 1,018
  • 2
  • 13
  • 34
  • You can use wait and notify primitives. – Sid Feb 26 '19 at 13:07
  • Does it start from the beginning or from where it left? – sirdan Feb 26 '19 at 13:14
  • These are things that you should learn from a good book or tutorial. There is no supported way to **pause** a thread (`Thread.suspend()` exists but should never be used and might get removed in the future), the only methods are `wait()` and `notify()` that a thread itself can use to wait for something, and abstractions build on that. Naturally, when the thread resumes, it does so from the point it waited. – Mark Rotteveel Feb 26 '19 at 15:18

1 Answers1

1

There are plenty of ways to manipulate threads.

suspend(): puts a thread in a suspended state and can be resumed using resume()

stop(): stops a thread

resume(): resumes a thread, which was suspended using suspend().

notify(): Wakes up a single thread.

wait(): makes the current thread wait.. (or sleep) until another thread invokes the notify() method for that thread.

notifyAll(): will wake up all sleeping (waiting) threads.

Note

In the latest versions of Java resume( ), suspend( ) and stop( ) has been deprecated

Question from OP

but when I wake it up, it resumes from where? Does it start from the beginning or from where it left?

Imagine a simple for-loop.

Starting thread 1.
Starting thread 2.
Thread 1: 0
Thread 2: 0
Thread 1: 1
Thread 2: 1
Pausing thread 1.
Thread 2: 2
Thread 2: 3
Thread 2: 4
Resuming thread 1.
Thread 1: 2
Thread 2: 5
Joel
  • 5,732
  • 4
  • 37
  • 65
  • Ok thank you, but when I wake it up, it resumes from where? Does it start from the beginning or from where it left? – sirdan Feb 26 '19 at 13:14
  • @sirdan it resumes where it was. Added example in answer. – Joel Feb 26 '19 at 13:15
  • 1
    You should **never** use `suspend()`, `stop()` or `resume()`. They have been deprecated in Java 1.2 as it is prone to deadlock or corruption/inconsistent state. See also [Why are Thread.stop, Thread.suspend and Thread.resume Deprecated?](https://docs.oracle.com/javase/8/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html) – Mark Rotteveel Feb 26 '19 at 15:21
  • 1
    You're answering a question from - what looks like - a beginner, and your answer starts with the suggestion that you can use `suspend()`, `stop()` and `resume()`. My comment is to indicate that is a bad idea (since Java 1.2 (1998), so not just 'latest versions') and it is not just deprecated, but actively discouraged by the Java documentation because it can be extremely harmful to use. – Mark Rotteveel Feb 26 '19 at 15:32