Java----synchronized的小测试

来源:互联网 发布:网络电视直播软件安装 编辑:程序博客网 时间:2024/06/06 12:58

方式一:方法内部修饰 

public class ThreadTest {public static List<Integer> forLey = new ArrayList<Integer>();public void doFun() {try {Thread.currentThread().sleep(600);} catch (Exception e) {e.printStackTrace();}synchronized (ThreadTest.class) {if (forLey.size() >= 1000)return;forLey.add(10);System.out.println(forLey.size());//打印1到1000}}public static void main(String[] args) {ThreadTest threadTest = new ThreadTest();for (int i = 0; i < 2000; i++) {Thread thread = new Thread(new MyRunnable(threadTest));thread.start();}}}class MyRunnable implements Runnable {private ThreadTest threadTest;public MyRunnable(ThreadTest threadTest) {this.threadTest = threadTest;}@Overridepublic void run() {threadTest.doFun();}}

 

 方式二:修饰方法

public class ThreadTest {public static List<Integer> forLey = new ArrayList<Integer>();// 修复实例方法,操作的ThreadTest的实例应为单实例(同一实例对象),可以注释CODE-1,打开CODE-2进行测试,程序会报错,或者打印不全// 或者将doFun方法加上 static静态修饰public synchronized void doFun() {try {Thread.currentThread().sleep(600);} catch (InterruptedException e) {e.printStackTrace();}if (forLey.size() >= 1000)return;forLey.add(10);System.out.println(forLey.size());// 打印1到1000}public static void main(String[] args) {ThreadTest threadTest = new ThreadTest(); // CODE-1for (int i = 0; i < 2000; i++) {// ThreadTest threadTest = new ThreadTest(); //CODE-2Thread thread = new Thread(new MyRunnable(threadTest));thread.start();}}}



 

 

  • 1

    Java SE1.6中的Synchronized http://ifeve.com/java-synchronized/

  • 2

    java synchronized http://liyanblog.cn/articles/2012/11/02/1351841479203.html

     

     

     

     

     

     

     

     

     

     

     

     

     

     


     

  • 0 0