搜索

首页  >  问答  >  正文

Java如何实现一个方法只能被同一个线程调用一次?

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

阿神阿神2888 天前547

全部回复(3)我来回复

  • 迷茫

    迷茫2017-04-18 10:32:00

    使用 Set 保存下已经调用过这个方法的 Thread 的 id,进入方法都先判断当前线程的 id 是否已经包含在该 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());
    
        // 方法内容
    }

    回复
    0
  • PHPz

    PHPz2017-04-18 10:32:00

    Thread.getCurrentThread.getId()

    回复
    0
  • 巴扎黑

    巴扎黑2017-04-18 10:32:00

    自定义一个 Thread 类
    在自定义的 Thread 上添加一个 boolean 成员用于判断

    例子

    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;
    }

    }

    运行结果
    Method test invoked !

    其他

    也可以用 ThreadLocal 解决

    回复
    0
  • 取消回复