非同步和多線程並不是一個同等關係,非同步是最終目的,多線程只是我們實現非同步的一種手段。非同步是當一個調用請求發送給被調用者,而調用者不用等待其結果的返回而可以做其它的事情。實現非同步可以採用多線程技術或則交給另外的進程來處理。 ...
一、多線程環境下的同步與非同步
同步:A線程要請求某個資源,但是此資源正在被B線程使用中,因為同步機制存在,A線程請求不到,怎麼辦,A線程只能等待下去。
package com.jalja.org.thread.demo01; public class Thread02 { public synchronized void method1(){ System.out.println("method1:"+Thread.currentThread().getName()); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } } public synchronized void method2(){ System.out.println("method2:"+Thread.currentThread().getName()); } public static void main(String[] args) { final Thread02 th=new Thread02(); Thread thread1=new Thread(new Runnable() { public void run() { th.method1(); } },"th1"); Thread thread2=new Thread(new Runnable() { public void run() { th.method2(); } },"th2"); thread1.start(); thread2.start(); } }
觀察輸出結果:method1:th1 在3秒後 method2:th2 輸出,這是因為method2() 與 method1()都是同步方法,而線程thread1 與 thread2操作的是同一個對象th,所以thread2在執行method2()方法時,需要先獲得到th對象的鎖。
非同步:A線程要請求某個資源,但是此資源正在被B線程使用中,因為沒有同步機制存在,A線程仍然請求的到,A線程無需等待。
package com.jalja.org.thread.demo01; public class Thread02 { public synchronized void method1(){ System.out.println("method1:"+Thread.currentThread().getName()); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } } public void method2(){ System.out.println("method2:"+Thread.currentThread().getName()); } public static void main(String[] args) { final Thread02 th=new Thread02(); Thread thread1=new Thread(new Runnable() { public void run() { th.method1(); } },"th1"); Thread thread2=new Thread(new Runnable() { public void run() { th.method2(); } },"th2"); thread1.start(); thread2.start(); } }
觀察輸出結果:method1:th1 與 method2:th2 同時輸出,這是因為method2 沒有加同步控制,所以線程thread2在執行method2()方法時不用去獲得執行許可權(對象鎖)。
二、數據的臟讀
我們在設計業務的時候一定要考慮業務的整體性,不然就會出現數據一致性問題。
package com.jalja.org.thread.demo01; public class Thread03 { private String name="zs"; private String passWorrd="123"; public synchronized void setValue(String name,String passWord){ this.name=name; try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } this.passWorrd=passWord; System.out.println("set:name="+this.name +" passWorrd="+this.passWorrd); } public void getValue(){ System.out.println("get:name="+this.name +" passWorrd="+this.passWorrd); } public static void main(String[] args) throws InterruptedException { final Thread03 th=new Thread03(); Thread thread=new Thread(new Runnable() { public void run() { th.setValue("LS", "456"); } }); thread.start(); Thread.sleep(100); th.getValue(); } }
結果:get:name=LS passWorrd=123 set:name=LS passWorrd=456 由結果可知get的數據顯然有問題,這是因為thread線程在set的時候,main線程在執行get方法。想要避免這種情況,我們就要保證當有線程在操作同一個對象的數據時,就不然其他線程也同時操作該對象的數據。這個情況我們在get方法上加 synchronized 關鍵字即可。