这一章节我们来讨论一下同步方法的隐患。
1.同步虽然给我们带来数据的一致性,但是,同时也降低了性能,代码清单:
package com.ray.deepintothread.ch02.topic_8; import java.sql.Time; /** * <br> * <br> * * @author RayLee * */ public class ThreatOfSynch { public static void main(String[] args) throws InterruptedException { MyService myService = new MyService(); ThreadOne threadOne = new ThreadOne(myService); Thread thread = new Thread(threadOne); thread.start(); ThreadTwo threadTwo = new ThreadTwo(myService); Thread thread2 = new Thread(threadTwo); thread2.start(); Thread.sleep(10000); System.out.println("application use time:" + (MyTimeUtil.END_TIME - MyTimeUtil.START_TIME)); } } class ThreadOne implements Runnable { private MyService myService; public ThreadOne(MyService myService) { this.myService = myService; } @Override public void run() { myService.service(); } } class ThreadTwo implements Runnable { private MyService myService; public ThreadTwo(MyService myService) { this.myService = myService; } @Override public void run() { myService.service(); } } class MyService { private void queryDataFromServer() { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } private void updateDataFromServer() { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } private void retrunDataFromServer() { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } public synchronized void service() { long startTime = System.currentTimeMillis(); if (MyTimeUtil.START_TIME == 0) { MyTimeUtil.START_TIME = startTime; } queryDataFromServer(); updateDataFromServer(); retrunDataFromServer(); long endTime = System.currentTimeMillis(); if (endTime > MyTimeUtil.END_TIME) { MyTimeUtil.END_TIME = endTime; } System.out.println("Thread name:" + Thread.currentThread().getName() + " use time:" + (endTime - startTime)); } } class MyTimeUtil { public static long START_TIME = 0; public static long END_TIME = 0; }
输出:
Thread name:Thread-0 use time:3000
Thread name:Thread-1 use time:3000
application use time:6000
2.结论
从输出可以看见,当我们使用同步方法的时候,特别是同步步骤非常多,而且某些步骤需要时间非常长的时候,就会出现上面的隐患,性能非常低下。
而且,其实我们在同步的时候,前后的查询不一定要求这么强的数据一致性,只需要中间更新的部分要求强一致性即可。
因此,我们将在下一章节引出另一个同步方式来解决这个隐患--同步代码块。
总结:这一章节我们主要讨论了同步方法的隐患。
这一章节就到这里,谢谢
------------------------------------------------------------------------------------
我的github:https://github.com/raylee2015/DeepIntoThread
目录:http://blog.csdn.net/raylee2007/article/details/51204573
目录:http://blog.csdn.net/raylee2007/article/details/51204573
时间: 2024-11-12 13:17:07