java 线程之对象的同步和异步
一、多線程環境下的同步與異步
同步: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 關鍵字即可。
?
轉載于:https://www.cnblogs.com/jalja/p/7158066.html
總結
以上是生活随笔為你收集整理的java 线程之对象的同步和异步的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: windows下运行多个tomcat的配
- 下一篇: 如何使用正则表达式