在 Class 非静态属性上应用同步
Apply synchronized on Class non static attribute
publicclass主类{
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
。
publicclass主类{ 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
。