這篇文章主要介紹了Java synchronized關(guān)鍵字使用方式及特性解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下

成都創(chuàng)新互聯(lián)是一家專注于成都網(wǎng)站設(shè)計、成都網(wǎng)站制作與策劃設(shè)計,榆次網(wǎng)站建設(shè)哪家好?成都創(chuàng)新互聯(lián)做網(wǎng)站,專注于網(wǎng)站建設(shè)10年,網(wǎng)設(shè)計領(lǐng)域的專業(yè)建站公司;建站業(yè)務(wù)涵蓋:榆次等地區(qū)。榆次做網(wǎng)站價格咨詢:028-86922220
synchronized 關(guān)鍵字是實現(xiàn)鎖的一種方式,是在jvm層面實現(xiàn)的非公平鎖,以下是使用synchronized的四種方式
synchronized 特性:
1.非公平鎖
2.可重入性
1.作用在方法上,保證了訪問同一個對象的同一個方法的線程同步
public synchronized void testFun(String str){
for(int i=0;i<15;i++){
System.out.println(str+",執(zhí)行中...");
}
}2.對象加鎖,保證同時訪問同一個對象的線程同步
public void testObject(String str){
synchronized (this){
for(int i=0; i<15;i++){
System.out.println(str+",執(zhí)行中");
}
}
}1,2 兩種加鎖方式在表現(xiàn)形式上是相同的
public static void main(String[] args){
ExecutorService executorService = Executors.newCachedThreadPool();
SynchronizeTest1 synchronizeTest1 = new SynchronizeTest1();
executorService.execute(new Runnable() {
@Override
public void run() {
synchronizeTest1.testObject("線程1");
}
});
executorService.execute(new Runnable() {
@Override
public void run() {
synchronizeTest1.testObject("線程2");
}
});
}3.作用在類上
public static void testClass(String str){
synchronized (SynchronizeTest2.class){
for(int i=0 ;i<15;i++){
System.out.println(str+",執(zhí)行中");
}
}
}4.作用在靜態(tài)方法上
public synchronized static void testStaticFun(String str){
for(int i=0;i<15;i++){
System.out.println(str+",執(zhí)行中");
}
}3,4 在表現(xiàn)形式上是一樣的
public static void main(String[] args){
ExecutorService executorService = Executors.newCachedThreadPool();
executorService.execute(new Runnable() {
@Override
public void run() {
testClass("線程1"); //可以替換為testStaticFun 方法
}
});
executorService.execute(new Runnable() {
@Override
public void run() {
testClass("線程2"); //可以替換為testStaticFun 方法
}
});
executorService.shutdown();
}以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持創(chuàng)新互聯(lián)。
本文標(biāo)題:Javasynchronized關(guān)鍵字使用方式及特性解析
新聞來源:http://www.chinadenli.net/article40/gjoseo.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供動態(tài)網(wǎng)站、品牌網(wǎng)站設(shè)計、品牌網(wǎng)站建設(shè)、微信小程序、網(wǎng)站營銷、靜態(tài)網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)