关于synchronized的认识一

来源:互联网 发布:婵真淘宝旗舰店整顿 编辑:程序博客网 时间:2024/05/29 19:57

生气synchronized的认识一[慢慢深入]

一:修饰方法 

1,synchronized  mothed

这种同步只是针对当前new出来的对象锁定,也就是说:new出1个当前对象,无论你开多少线程去访问该对象中任意一个synchronized 方法,都得等前一个调用结束后才能调用,顺序不定。 当然你new 多个对象,多个线程并且分别调用不同的方法,则synchronized 是没有作用的。这时候就得看2了。。。

2,synchronized static  mothed

加static是在上面的基础上,个人认为是给当前对象加了一个全局锁,不论你是new出不同对象还是直接在线程中调用。该类的synchronized只能由一个线程去调用,全局锁定,该线程结束后其他线程继续去调用,顺序不定。

 

贴上两个测试类:

public class TestSynchronized {public static void main(String[] args) throws InterruptedException {TestThread testThread=new TestThread();new Thread(testThread).start();new Thread(testThread).start();TestThread testThread1=new TestThread();new Thread(testThread1).start();new Thread(testThread1).start();}public static final synchronized void synch1(){System.out.println("1 star!"+new Date().getTime());try {Thread.sleep(10000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("1 over!"+new Date().getTime());}public static final synchronized void synch2(){System.out.println("2 star!"+new Date().getTime());try {Thread.sleep(10000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("2 over!"+new Date().getTime());}}
public class TestThread implements Runnable {private TestSynchronized t=new TestSynchronized();public TestThread(){}public TestThread(TestSynchronized tt){t=tt;}private int i=0;public void run() {this.i++;try {if(i%2==0){System.out.println(i+"调用第一个方法");t.synch1();System.out.println(i+"调用结束。。。。。");}else{System.out.println(i+"调用第二个方法");t.synch2();System.out.println(i+"调用结束。。。。。");}Thread.sleep(10000);} catch (InterruptedException e) {e.printStackTrace();}}}


 

二:方法块

原创粉丝点击