简体   繁体   中英

How to lock/pause the thread running in another Class?

I have two classes. In Class1 I have a thread and in Class2 I have to pause/lock that thread which will be started immediately after the login. In my scenario, after the login (which is implemented in Class2) the Thread has to be made wait for some more additional login and getting data from DB. Please let me know how to control the Thread running in the other class from different class.

Class1:

public class Class1{
 Class2 cls2 = new Class2();
 cls2.logon();
 // login which will start the thread in the Class2 as well
 // Please suggest what should be done here

 // DB realated stuff need be done here
 // Have to unlock/resume the thread in Class2
}

Class2:

public class Class2{
 public void receiveMessage(String str){
   new StringProcessor(str);
 }

 public class StringProcessor implements Runnable {
  //do some stuff but have to wait for the DB related stuff in Class1
 }

 public void logon(){
  //Will create/logon the connection and the message will be start arriving
 }

}

Actually after login there will be TCP/IP connection to receive the messages. The method receiveMessage() will be called whenever the message arrives. But I have to pause that

Cheers, Sakthi. S

There are several approaches.

The wrong one is to use Thread.suspend/resume/destroy since they are deprecated and deadlock-prone.

You can either...

  1. Implement your own signaling mechanism by using Object.wait, Object.notifyAll.
  2. Use the Semaphore class or any other class in java.util.concurrent that suits your needs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM