繁体   English   中英

当一个方法已经被另一个线程执行时跳过它

[英]Skipping a method when it is already executed by another thread

我的问题与这个有关: 如果另一个线程正在执行它,则退出一个方法

有一种方法由多个线程执行。 如果一个线程正在执行该方法,则任何其他线程都应该退出。 我的解决方案是这样的:

public class ReentrantLockTest implements Runnable {

    private static final ReentrantLock LOCK = new ReentrantLock();

    @Override
    public void run() {
        if (LOCK.tryLock()) {
            System.out.println("Aquired. Thread "  + Thread.currentThread().getId());
            try {
                // do stuff here

            } catch (Exception e) {
                // handle errors
            } finally {
                // release the lock
                LOCK.unlock();
            }
        }
    }

这对我来说似乎很好,但在生产中有时会发生锁仍未释放,因此除非我重新启动系统,否则该方法根本不会执行。

所以我有两个问题:1.锁怎么可能没有被释放? 2. 测试此类代码的好方法是什么? 只是在一个循环中运行它,并希望它会在某个时候崩溃,如果有一个错误似乎不是一个好的解决方案。

您应该使用synchronized关键字。 这确保只有一个线程同时执行一段代码。

将您的方法更改为:

public synchronised void run() {
   //your code
}
package thread;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ReentrantLockTest implements Runnable 
{
    private static final ReentrantLock LOCK = new ReentrantLock();
    @Override
    public void run() 
    {
        boolean done = false; 
        while (!done) 
        {
            boolean ans=LOCK.tryLock();
        if(ans) 
            {
            System.out.println("Aquired. Thread "  + Thread.currentThread().getId());
            try {
                // do stuff here
                System.out.println(Thread.currentThread().getName()+ " in try block");
                done = true;    
            }catch (Exception e) {
                // handle errors
            } finally {
                // release the lock
                LOCK.unlock();
                System.out.println(Thread.currentThread().getName()+" unlock");
                }
            }
        else
            { 
            System.out.println(Thread.currentThread().getName()  + " waiting for lock"); 
            try
            {Thread.sleep(1000);} 
            catch(InterruptedException e) 
                {e.printStackTrace();} 
            }
      }
   }
}


public class ReentrantLockDemo2 
{
    public static void main(String[] args) 
    {
        ExecutorService pool=Executors.newFixedThreadPool(5);
        Runnable t1=new ReentrantLockTest();
        Runnable t2=new ReentrantLockTest();
        Runnable t3=new ReentrantLockTest();
        Runnable t4=new ReentrantLockTest();

        pool.execute(t1);
        pool.execute(t2);
        pool.execute(t3);
        pool.execute(t4);

        pool.shutdown();
        System.out.println("Main Close");
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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