synchronized的类锁和对象锁区别
作者:互联网
对象锁:
public class ThreadExceptionDemo { public static void main(String[] args) throws InterruptedException { new Thread(new Runnable() { @SneakyThrows @Override public void run() { ThreadExceptionDemo threadExceptionDemo = new ThreadExceptionDemo(); threadExceptionDemo.int1(); // int3(); } }).start(); new Thread(new Runnable() { @SneakyThrows @Override public void run() { ThreadExceptionDemo threadExceptionDemo = new ThreadExceptionDemo(); threadExceptionDemo.int2(); // int4(); } }).start(); } public synchronized void int1() throws InterruptedException { System.out.println("int1........."); Thread.sleep(5000); } public synchronized void int2() throws InterruptedException { System.out.println("int2........."); Thread.sleep(5000); } public synchronized static void int3() throws InterruptedException { System.out.println("int3........."); Thread.sleep(5000); } public synchronized static void int4(){ System.out.println("int4........."); } }
结果:对象锁会同时获取到锁
int1.........
int2.........
类锁:
public class ThreadExceptionDemo { public static void main(String[] args) throws InterruptedException { new Thread(new Runnable() { @SneakyThrows @Override public void run() { // ThreadExceptionDemo threadExceptionDemo = new ThreadExceptionDemo(); // threadExceptionDemo.int1(); int3(); } }).start(); new Thread(new Runnable() { @SneakyThrows @Override public void run() { // ThreadExceptionDemo threadExceptionDemo = new ThreadExceptionDemo(); // threadExceptionDemo.int2(); int4(); } }).start(); } public synchronized void int1() throws InterruptedException { System.out.println("int1........."); Thread.sleep(5000); } public synchronized void int2() throws InterruptedException { System.out.println("int2........."); Thread.sleep(5000); } public synchronized static void int3() throws InterruptedException { System.out.println("int3........."); Thread.sleep(5000); } public synchronized static void int4(){ System.out.println("int4........."); } }
结果:(in3输出后延迟5秒输出int4)
int3.........
int4.........
并发情况下,类锁需要等持有线程释放锁才可以,获取资源,
标签:ThreadExceptionDemo,synchronized,区别,void,Thread,类锁,.........,new,public 来源: https://www.cnblogs.com/leeego-123/p/16364286.html