在类非静态属性上应用同步



public class MainClass { public static void main(String[] args) {

T1 ok = new T1();
T2 ok1 = new T2();
ok.start();
ok1.start();
}

}

public class T1 extends Thread {
@Override
public void run() {
DemoClass q = new DemoClass();
for (int i = 0; i <= 5; i++)
try {
q.demoMethod();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

public class T2 extends Thread {
@Override
public void run() {
DemoClass q = new DemoClass();
for (int i = 0; i <= 5; i++)
try {
q.demoMethod1();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

public class DemoClass {
String s = "";
String s1 = "";
public void demoMethod() throws InterruptedException {
System.out.println(Thread.currentThread().getName() + " Entered m1");
synchronized (s) {
System.out.println(Thread.currentThread().getName() + " Inside m1 ");
Thread.sleep(5000);
}
System.out.println(Thread.currentThread().getName()+" m1");
}
public void demoMethod1() throws InterruptedException {
System.out.println(Thread.currentThread().getName() + " Entered m2");

System.out.println(Thread.currentThread().getName() + " Inside m2 ");
Thread.sleep(5000);

System.out.println(Thread.currentThread().getName()+" m2");
}

}

即使我创建了 DemoClass 的单独对象,然后通过单独的线程调用单独的方法。 为什么一次只有一个线程工作?

或者,如果有人可以建议我们将在 DemoClass 中调用哪种类型的锁定代码

您正在同步s,这始终是同一个对象。

别这样。 如果要同步任何内容,请在this上同步。

最新更新