一:synchronized示例
1、主类
package locks; /** * @author chunxiaozhang * @date 2020/4/9 10:06 * @desc */ public class MainDemo { public static void main(String[] args) { final Peopele p = new Peopele (); final Peopele p2 = new Peopele (); //线程1 new Thread ( new Runnable ( ) { @Override public void run() { p2.speak_obj ();; } } ,"thread_1").start(); //线程2 new Thread ( new Runnable ( ) { @Override public void run() { p.speak_static_void(); } } ,"thread_2").start(); //线程3 new Thread ( new Runnable ( ) { @Override public void run() { p.speak_static_void (); } } ,"thread_3").start(); } }
2、测试类
package locks; /** * @author chunxiaozhang * @date 2020/4/9 11:05 * @desc */ public class Peopele { private static int sta_num = 1; private int num = 1; //无锁部分 public void speak() { System.out.println ( Thread.currentThread ().getName () + ":开始。。。。。。。。。。" ); try { Thread.sleep ( 1000 ); System.out.println ( Thread.currentThread ().getName () + ":sta_num+1=" + (sta_num+1)); System.out.println ( Thread.currentThread ().getName () + ":num+1=" + (num+1)); } catch (InterruptedException e) { e.printStackTrace ( ); } System.out.println ( Thread.currentThread ().getName () + ":结束。。。。。。。。。。" ); } //用于对象上 public void speak_this() { synchronized (this) { System.out.println ( Thread.currentThread ().getName () + ":开始。。。。。。。。。。" ); try { Thread.sleep ( 3000 ); } catch (InterruptedException e) { e.printStackTrace ( ); } System.out.println ( Thread.currentThread ().getName () + ":结束。。。。。。。。。。" ); } } //用于类上 public void speak_class() { synchronized (Peopele.class) { System.out.println ( Thread.currentThread ().getName () + ":开始。。。。。。。。。。" ); try { Thread.sleep ( 3000 ); } catch (InterruptedException e) { e.printStackTrace ( ); } System.out.println ( Thread.currentThread ().getName () + ":结束。。。。。。。。。。" ); } } //用于任意对象 public void speak_obj() { synchronized (new Object ()) { System.out.println ( Thread.currentThread ().getName () + ":开始。。。。。。。。。。" ); try { Thread.sleep ( 3000 ); } catch (InterruptedException e) { e.printStackTrace ( ); } System.out.println ( Thread.currentThread ().getName () + ":结束。。。。。。。。。。" ); } } //用于方法上 public synchronized void speak_void() { System.out.println ( Thread.currentThread ().getName () + ":开始。。。。。。。。。。" ); try { Thread.sleep ( 3000 ); } catch (InterruptedException e) { e.printStackTrace ( ); } System.out.println ( Thread.currentThread ().getName () + ":结束。。。。。。。。。。" ); } //用于静态方法上 public synchronized static void speak_static_void() { System.out.println ( Thread.currentThread ().getName () + ":开始。。。。。。。。。。" ); try { Thread.sleep ( 3000 ); } catch (InterruptedException e) { e.printStackTrace ( ); } System.out.println ( Thread.currentThread ().getName () + ":结束。。。。。。。。。。" ); } }