用代码说话:synchronized关键字和多线程访问同步方法的7种情况 (2)

同时访问同步方法与非同步方法

解释:synchronize的关键字只对fun1起作用,不会对其他方法造成影响。也就是说同步方法不会对非同步方法造成影响,两个方法并行执行。

### 5. 访问同一个对象的不同的普通同步方法

public class Demo5 implements Runnable {     static Demo5 instance = new Demo5();     @Override     public void run() {         if (Thread.currentThread().getName().equals("Thread-0")){             fun1();         }else{             fun2();         }     }     public synchronized void fun1() {         System.out.println(Thread.currentThread().getName() + "开始运行");         try {             Thread.sleep(2000);         } catch (InterruptedException e) {             e.printStackTrace();         }         System.out.println(Thread.currentThread().getName() + "fun1运行结束");     }     public synchronized void fun2() {         System.out.println(Thread.currentThread().getName() + "fun2开始运行");         try {             Thread.sleep(2000);         } catch (InterruptedException e) {             e.printStackTrace();         }         System.out.println(Thread.currentThread().getName() + "运行结束");     }     public static void main(String[] args) {         Thread thread1 = new Thread(instance);         Thread thread2 = new Thread(instance);         thread1.start();         thread2.start();         while (thread1.isAlive() || thread2.isAlive()) {         }         System.out.println("finished");     } }

结果:顺序执行。

访问同一个对象的不同的普通同步方法

解释:两个方法共用了instance对象锁,两个方法无法同时运行,只能先后运行。

6. 同时访问静态synchronized和非静态的synchronized方法 public class Demo6 implements Runnable{     static Demo6 instance = new Demo6();     @Override     public void run() {         if (Thread.currentThread().getName().equals("Thread-0")){             fun1();         }else{             fun2();         }     }     public static synchronized void fun1() {         System.out.println(Thread.currentThread().getName() + "开始运行");         try {             Thread.sleep(2000);         } catch (InterruptedException e) {             e.printStackTrace();         }         System.out.println(Thread.currentThread().getName() + "fun1运行结束");     }     public synchronized void fun2() {         System.out.println(Thread.currentThread().getName() + "fun2开始运行");         try {             Thread.sleep(2000);         } catch (InterruptedException e) {             e.printStackTrace();         }         System.out.println(Thread.currentThread().getName() + "运行结束");     }     public static void main(String[] args) {         Thread thread1 = new Thread(instance);         Thread thread2 = new Thread(instance);         thread1.start();         thread2.start();         while (thread1.isAlive() || thread2.isAlive()) {         }         System.out.println("finished");     } }

结果:两个线程并行执行

同时访问静态synchronized和非静态的synchronized方法

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zwxydx.html