自定义一个 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 解决