例:
ThisClass.staticMethod(Object... parameters);
Run Code Online (Sandbox Code Playgroud)
将由其他对象的多个实例同时访问.
当它们同时使用相同的静态方法时,是否会与其他对象有任何依赖关系?
仅当方法使用静态对象或参数由其他实例共享时.
示例:Math.max(int a,int b)是一个静态方法,但不使用任何静态对象,因此没有依赖项.
示例2:此处所有调用共享相同的结果变量,对staticMethod的两次并行调用可能导致错误的结果.
private static int result = 0;
private static int staticMethod(Object... args)
{
result = args.length;
//Do Something
return result;
}
Run Code Online (Sandbox Code Playgroud)
示例3:如果没有共享参数,则此一个是线程安全的,每个调用都有自己的结果实例.
private static int staticMethod(Object... args)
{
int result = 0;
result = args.length;
//Do something
return result;
}
Run Code Online (Sandbox Code Playgroud)
示例4:这使用类作为锁来防止对类函数的并行访问.只有一次对staticMethod的调用会执行所有其他的wait
private static int result = 0;
private static synchronized int staticMethod(Object... args)
{
result = args.length;
//Do Something
return result;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3795 次 |
| 最近记录: |