Interactions between Java threads

108 views Asked by At

I have two classes (A & B) which implements Runnable.

Both threads are executed in this way:

A a = new A();
new Thread(a).start();

B b = new B();
new Thread(b).start();

I need to stop/wait/resume thread A inside thread B.

How does it's possible?

2

There are 2 answers

2
Sergey Maksimenko On BEST ANSWER

Actually, you can't just stop tread.As markspace commented, it is possible, but you should do it carefully and in some special cases

Java Thread Primitive Deprecation

Why is Thread.stopdeprecated?

Because it is inherently unsafe. Stopping a thread causes it to unlock all the monitors that it has locked. (The monitors are unlocked as theThreadDeath exception propagates up the stack.) 

4
AdamSkywalker On

There is no way to pause/resume threads in java. If you want this, you should implement it on your own - for example wait on some condition.

Here you can see an example, how to make thread wait on mutex and later notify it. Anyway, it is possible only if thread performs some periodical stuff. If thread action is solid, there is no way to achieve your goal.