java - 同步方法同时执行
问题描述
根据 synchronized 关键字,如果应用于方法,则它会获取对象锁,并且具有相同实例的多个方法将无法同时执行这些方法。
但在下面的示例中,执行是同时发生的。请看一看:-
public class ncuie extends Thread{
int b;
ncuie(int a){
b=a;
}
public synchronized void abc() throws InterruptedException {
for (int i = 0; i < 10; i++) {
System.out.println("thread 1 "+i);
}
}
public synchronized void pqr() throws InterruptedException {
for (int i = 0; i < 10; i++) {
System.out.println("thread 2 "+i);
}
}
public void run() {
try {
if(b==5) {
abc();
}
if(b==10) {
pqr();
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
Thread t=new ncuie(5);
Thread t1=new ncuie(10);
t.start();
t1.start();
}
}
根据输出,有时执行线程 1,有时执行线程 2。理想情况下,只有一个线程应该获得锁并完成它的执行,然后才应该启动第二个线程。
输出:-
thread 1 0
thread 1 1
thread 2 0
thread 2 1
thread 2 2
thread 1 2
thread 1 3
thread 1 4
thread 1 5
thread 1 6
thread 1 7
thread 1 8
thread 2 3
thread 2 4
thread 2 5
thread 2 6
thread 1 9
thread 2 7
thread 2 8
thread 2 9
解决方案
如果某些方法以这样的方式更改内部状态,以至于在同一实例上运行的其他方法会遇到麻烦,您通常会在您的实例上进行同步。在当前实例上同步 ( ) 是您通过在非静态方法上使用关键字或编写.this
synchronized
synchronized(this) {...}
如果您的方法以这样的方式更改状态,即使在类的不同实例上操作的方法也会受到影响,您可以在类对象上进行同步。你通过写作来做到这一点synchronized(MyClass.class) {...}
。
如果你有静态方法需要与同一个类的其他静态方法同步,你可以通过synchronized
在静态方法上使用关键字来获得类对象上的同步。
请注意,实例级同步和类级同步是完全独立的,这意味着,当类同步方法运行时,实例同步方法不会被阻塞。
在您的情况下,您在实例上同步,并且您有两个不同的实例,因此它们不会相互阻塞。
推荐阅读
- c# - 每次刷新后嵌套的树视图常量
- typescript - 学习循环地图问题
- react-native - navigation.push 不添加新路线
- ios - 为什么我会收到警告“表达式从 'xx 隐式强制”?去任何'”?
- python-3.x - 全局变量不能以对话框形式工作
- pyspark - 如何在 Pyspark 数据框中使用 POS 标记执行词形还原(不使用 Pandas)
- python - 为什么 Python 仍然带有我认为与当前版本 19 相比非常旧的 pip 版本 9?
- apache - 加载 ioncube_loader_lin_5.4.so 失败:ioncube_loader_lin_5.4.so:无法打开共享对象文件:没有这样的文件或目录
- lua - 导入类方法
- .net - 实体框架属性在未请求时具有值