How interrupt/stop a thread in Java?

后端 未结 8 1788
失恋的感觉
失恋的感觉 2020-12-05 07:48

I\'m trying to stop a thread but I can\'t do that :

public class Middleware {

public void read() {
    try {
        socket = new Socket(\"192.168.1.8\", 20         


        
8条回答
  •  星月不相逢
    2020-12-05 08:44

    Rather than using Thread.stop() or Thread.interrupt() you can go for the external locks. Basically, when you try to utilize an intrinsic lock most of the time any interrupt you perform on the thread is uncontrollable.

    A re-entrant lock provides you the methods as mentioned below

    lock() 
    unlock() 
    tryLock() 
    lockInterruptibly() 
    isHeldByCurrentThread() 
    getHoldCount() 
    

    Check the below example

    final ReentrantLock reentrantLock = new ReentrantLock();    
        @Override
        public void performTask() {
            reentrantLock.lock();
            try { 
                 System.out.println(Thread.currentThread().getName() + ": Lock acquired.");
                 System.out.println("Processing...");
                 Thread.sleep(2000);
            } catch (InterruptedException e) {
                 e.printStackTrace();
            } finally {
                 System.out.println(Thread.currentThread().getName() + ": Lock released.");
             reentrantLock.unlock();
                }
        }
    

    This makes your code elegant and handle the interrupt in a better way.

提交回复
热议问题