網站首頁 編程語言 正文
synchronized關鍵字的語法結構
synchronized(this){
//同步代碼
}
或者在方法上添加了synchronized的,如下
public synchronized void accessVal(int newVal){
//同步代碼
}
實例:(可以拿去Idea上復制粘貼運行一下)
/**
* 定義程序員類
*/
class Programmer{
private String name;
public Programmer(String name){
this.name = name;
}
/**
* 打開電腦
*/
synchronized public void computer(){
try {
System.out.println(this.name + " 接通電源");
Thread.sleep(500);
System.out.println(this.name + " 按開機按鍵");
Thread.sleep(500);
System.out.println(this.name + " 系統啟動中");
Thread.sleep(500);
System.out.println(this.name + " 系統啟動成功");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* 編碼
*/
synchronized public void coding(){
try {
System.out.println(this.name + " 雙擊Idea");
Thread.sleep(500);
System.out.println(this.name + " Idea啟動完畢");
Thread.sleep(500);
System.out.println(this.name + " 開開心心的寫代碼");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
* 打開電腦的工作線程
*/
class Working1 extends Thread{
private Programmer p;
public Working1(Programmer p){
this.p = p;
}
@Override
public void run() {
this.p.computer();
}
}
/**
* 編寫代碼的工作線程
*/
class Working2 extends Thread{
private Programmer p;
public Working2(Programmer p){
this.p = p;
}
@Override
public void run() {
this.p.coding();
}
}
public class TestSyncThread {
public static void main(String[] args) {
Programmer p = new Programmer("張三");
new Working1(p).start();
new Working2(p).start();
}
}
原文鏈接:https://blog.csdn.net/m0_73944607/article/details/130669381
- 上一篇:沒有了
- 下一篇:沒有了
相關推薦
- 2022-04-28 C++Stack棧類模版實例詳解_C 語言
- 2022-09-13 Golang優雅保持main函數不退出的辦法_Golang
- 2022-08-04 解析Mybatis對sql表的一對多查詢問題_MsSql
- 2022-09-16 Pandas?篩選和刪除目標值所在的行的實現_python
- 2023-04-29 Python腳本修改Maya?ASCII文件路徑方法實現_python
- 2022-04-21 C#?TrackBar拖動條改變滑塊顏色_C#教程
- 2022-09-22 右值引用(C++11)
- 2022-09-25 nginx平滑升級、nginx支持的kill信號
- 欄目分類
-
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支