如題。Java 如何實現一個方法只能被同一個線程調用一次 ,同一個線程調用第二次的時候可以拋異常。
2 回答

慕勒3428872
TA貢獻1848條經驗 獲得超6個贊
自定義一個 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/150
提交
取消