日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

java syncr_JAVA基础—Synchronized线程同步机制

發布時間:2023/12/10 编程问答 21 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java syncr_JAVA基础—Synchronized线程同步机制 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Synchronize的使用場景

Synchronize可以使用在一下三種場景,對應不同的鎖對象

場景

synchronized代碼塊

synchronized方法

synchronized靜態方法

鎖對象

任意對象

this 對象

該類的字節碼對象 *.class

沒有同步代碼實例

public class SyncSample {

public static void main(String[] args) {

Couplet couplet = new Couplet();

for (int i = 1; i < 1000; i++)

new Thread() {

public void run() {

int r = new Random().nextInt(2);

if (r % 2 == 0){

couplet.first();

}else {

couplet.second();

}

}

}.start();

}

}

class Couplet {

public void first() {

System.out.printf("琴");

System.out.printf("瑟");

System.out.printf("琵");

System.out.printf("琶");

System.out.println();

}

public void second() {

System.out.printf("魑");

System.out.printf("魅");

System.out.printf("魍");

System.out.printf("魎");

System.out.println();

}

}

運行結果

...

魑魅魍魎

琴瑟琵琶

琴瑟琴瑟琵琶

魍魎

琴瑟琵琶

琴瑟琵魅魍魎

魑魅瑟琵琶

1. synchronized代碼塊 解決

class Couplet {

//創建鎖對象 可以是任意對象 也可用當前對象this

Object lock = new Object();

public void first() {

//代碼塊 需要有鎖對象

synchronized (lock) {

System.out.printf("琴");

System.out.printf("瑟");

System.out.printf("琵");

System.out.printf("琶");

System.out.println();

}

}

public void second() {

//代碼塊 需要有鎖對象

synchronized (lock) {

System.out.printf("魑");

System.out.printf("魅");

System.out.printf("魍");

System.out.printf("魎");

System.out.println();

}

}

}

運行結果

琴瑟琵琶

魑魅魍魎

琴瑟琵琶

魑魅魍魎

2. synchronized方法 同步方法解決

class Couplet {

//同步方法 this當前對象就是鎖對象

public synchronized void first() {

System.out.printf("琴");

System.out.printf("瑟");

System.out.printf("琵");

System.out.printf("琶");

System.out.println();

}

//代碼塊與同步方法 同步時 使用this當前對象

public void second() {

synchronized (this){

System.out.printf("魑");

System.out.printf("魅");

System.out.printf("魍");

System.out.printf("魎");

System.out.println();

}

}

}

運行結果

琴瑟琵琶

魑魅魍魎

琴瑟琵琶

魑魅魍魎

3. synchronized靜態方法

class Couplet {

//靜態同步方法 當前對象.class 的字節碼對象就是鎖對象

public synchronized static void first() {

System.out.printf("琴");

System.out.printf("瑟");

System.out.printf("琵");

System.out.printf("琶");

System.out.println();

}

//代碼塊與靜態方法同步時 使用當前字節碼鎖對象

public void second() {

synchronized (Couplet.class){

System.out.printf("魑");

System.out.printf("魅");

System.out.printf("魍");

System.out.printf("魎");

System.out.println();

}

}

}

運行結果

琴瑟琵琶

魑魅魍魎

琴瑟琵琶

魑魅魍魎

總結

以上是生活随笔為你收集整理的java syncr_JAVA基础—Synchronized线程同步机制的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。