synchronized【Java】中使用的demo
生活随笔
收集整理的這篇文章主要介紹了
synchronized【Java】中使用的demo
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
synchronized【Java】中使用的demo
沒有synchronized的效果:
package Action;public class syn {static int count=10;static Object lock=new Object();public static void main(String[] args) {new Thread(new Runnable() {@Overridepublic void run() {while (true) {if(count<=0) {System.out.println("內部線程:結束");break;} // synchronized(lock) {count--;System.out.println("內部線程:"+count); // }try {Thread.sleep(100);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}).start();while (true) {if(count<=0) {System.out.println("外部線程:結束");break;} // synchronized (lock) {count--;System.out.println("外部線程:"+count); // }try {Thread.sleep(100);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}} }很明顯,在沒有使用【鎖】的時候數據出現了錯誤。?
有synchronized的效果:
package Action;public class syn {static int count=10;static Object lock=new Object();public static void main(String[] args) {new Thread(new Runnable() {@Overridepublic void run() {while (true) {if(count<=0) {System.out.println("內部線程:結束");break;}synchronized(lock) {count--;System.out.println("內部線程:"+count);}try {Thread.sleep(100);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}).start();while (true) {if(count<=0) {System.out.println("外部線程:結束");break;}synchronized (lock) {count--;System.out.println("外部線程:"+count);}try {Thread.sleep(100);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}} }效果很明顯,沒有數據錯誤。?
?synchronized不僅可以修飾代碼塊,還可以修飾方法、實例對象、class對象。
如果鎖的是類對象的話,盡管new多個實例對象,但他們仍然是屬于同一個類依然會被鎖住,即線程之間保證同步關系。
總結
以上是生活随笔為你收集整理的synchronized【Java】中使用的demo的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2022跨年代码(HTML·资源都是网上
- 下一篇: 【蓝桥杯Java_C组·从零开始卷】第三