package com.swt.lock; public class Test02 { public static void main(String[] args) throws InterruptedException { Thread thread = new Thread(new Runnable() { @Override public void run() { SyncMethod syncMethod = new SyncMethod(); syncMethod.sysn1(); } }); thread.start(); thread = new Thread(new Runnable() { @Override public void run() { SyncMethod syncMethod = new SyncMethod(); syncMethod.sysn2(); } }); thread.start(); thread.join(); } } class SyncMethod { public synchronized void sysn1() { for (int i = 0; i < 100; i++) { System.out.println("sysn1 " + i); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } public synchronized void sysn2() { for (int i = 0; i < 100; i++) { System.out.println("sysn2 " + i); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } }
输出结果可以看到,两个线程是交替执行。
sysn1 0 sysn2 0 sysn2 1 sysn1 1 sysn2 2 sysn1 2 sysn2 3 sysn1 3 sysn2 4
package com.swt.lock; public class Test02 { public static void main(String[] args) throws InterruptedException { SyncMethod syncMethod = new SyncMethod(); Thread thread = new Thread(new Runnable() { @Override public void run() { syncMethod.sysn1(); } }); thread.start(); thread = new Thread(new Runnable() { @Override public void run() { syncMethod.sysn2(); } }); thread.start(); thread.join(); } } class SyncMethod { public synchronized void sysn1() { for (int i = 0; i < 100; i++) { System.out.println("sysn1 " + i); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } public synchronized void sysn2() { for (int i = 0; i < 100; i++) { System.out.println("sysn2 " + i); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } }
输出结果可以看到,两个线程是顺序执行
sysn1 0 sysn1 1 sysn1 2 ... sysn1 98 sysn1 99 sysn2 0 sysn2 1 sysn2 2 sysn2 3