1、静态方法加锁 public synchronized static void doPrint(String name){ try{ System.out.println( name + " begin: *************"); Thread.sleep(10000); System.out.println( name +" end: *************"); }catch (Exception e){ e.printStackTrace(); } } 2、普通方法加锁 public synchronized void doPrint(){ try{ System.out.println( this.name + " begin: *************"); Thread.sleep(10000); System.out.println( this.name +" end: *************"); }catch (Exception e){ e.printStackTrace(); } } 3、代码块加对象锁 public void doWrite(){ try{ System.out.println("begin:------------------" + this.name); synchronized (this){ System.out.println( this.name + " begin: *************"); Thread.sleep(10000); System.out.println( this.name +" end: *************"); } System.out.println("end:------------------" + this.name); }catch (Exception e){ e.printStackTrace(); } }
4、代码块加普通对象锁
public void doWrite(){ try{ System.out.println("begin:------------------" + this.name); synchronized (obj){ System.out.println( this.name + " begin: *************"); Thread.sleep(10000); System.out.println( this.name +" end: *************"); } System.out.println("end:------------------" + this.name); }catch (Exception e){ e.printStackTrace(); } }
验证了以上四种加锁方式
1和4表示只要当前线程未执行完,其他线程都会阻塞
2和3表示如果多个线程访问同一个实例对象,则当前线程未执行完,其他线程都会阻塞,否则不同实例对象在不同的线程执行互不影响