Java中A类有2个同步方法,B类有2个静态同步方法,这两种情况是否允许2个线程访问
public class ThreadTest {
public static synchronized void m2() {
System.out.println("static sync m2");
System.out.println("current"+Thread.currentThread());
try { Thread.sleep(2000); }
catch (InterruptedException ie) {}
}
public static void main(String[] args) throws InterruptedException {
Thread t3 = new Thread() {
public void run() {
ThreadTest.m2();
}
};
t3.start();
t3.sleep(2000);
Thread.sleep(500); // which thread are we sleeping here?
System.out.println("t3.getState"+t3.getState());
}
}
如果我们创建另一个线程 t1 并访问 ThreadTest.m2();这里面?是的,这是允许的,为什么这是静态的并且是类级别的。但是如果我们有非静态方法,那么线程1和2就不允许访问该方法
public class ThreadTest {
public static synchronized void m2() {
System.out.println("static sync m2");
System.out.println("current"+Thread.currentThread());
try { Thread.sleep(2000); }
catch (InterruptedException ie) {}
}
public static void main(String[] args) throws InterruptedException {
Thread t3 = new Thread() {
public void run() {
ThreadTest.m2();
}
};
t3.start();
t3.sleep(2000);
Thread.sleep(500); // which thread are we sleeping here?
System.out.println("t3.getState"+t3.getState());
}
}
If we create another thread t1 and access ThreadTest.m2(); inside of this? yes this will be allowed, why this is static and it class level. But if we have non-static methods, then Thread 1 and 2 are not allowed to access the method
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请查看:Java 同步静态方法:锁定对象或类< /a>
问候。
编辑:特别是这个答案:Java同步静态方法:锁定对象或类
Please check this out: Java synchronized static methods: lock on object or class
Regards.
Edit: in particular, this answer: Java synchronized static methods: lock on object or class