Java如何实现一个方法只能被同一个线程调用一次?
阿神
阿神 2017-04-18 10:30:00
0
3
540

如题。Java 如何实现一个方法只能被同一个线程调用一次 ,同一个线程调用第二次的时候可以抛异常。

阿神
阿神

闭关修行中......

reply all(3)
迷茫

Use Set to save the id of the Thread that has called this method. When entering the method, first determine whether the id of the current thread is already included in the Set:

private final Set<Long> THREADS = new HashSet<>();

public void someMethod () {
    if (THREADS.contains(Thread.currentThread().getId())) {
        throw new RuntimeException("该线程不能再调用这个方法");
    }
    THREADS.add(Thread.currentThread().getId());

    // 方法内容
}
PHPzhong

Thread.getCurrentThread.getId()

巴扎黑

Customize a Thread class
Add a boolean member to the customized Thread for judgment

Example

public class Main
{
public static void main(String[] args)

{
    new MyThread(new Runnable()
    {
            @Override
            public void run()
            {
                test();
                test();
                test();
                test();
            }
    }).start();
    
}

public static void test()
{
    Thread t = Thread.currentThread();
    if ( !(t instanceof MyThread) || ((MyThread)t).isTestInvoked() )
        return ;
    
    System.out.println("Method test invoked !");
}

public static class MyThread extends Thread
{
    public MyThread(Runnable r)
    {
        super(r);
    }

    public MyThread()
    {
        super();
    }

    public boolean isTestInvoked()
    {
        boolean result = methodTestInvoked;
        methodTestInvoked = true;
        return result;
    }

    private boolean methodTestInvoked = false;
}

}

Run results
Method test invoked!

Others

You can also use ThreadLocal to solve it

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template