更新時間:2022-06-15 10:36:22 來源:動力節點 瀏覽1131次
Java中的同步是控制多個線程對任何共享資源的訪問的能力。
在我們希望只允許一個線程訪問共享資源的情況下,Java 同步是更好的選擇。
同步主要用于
防止線程干擾。
防止一致性問題。
有兩種類型的同步
進程同步
線程同步
在這里,我們將只討論線程同步。
線程同步有互斥和線程間通信兩種。
1.互斥
同步方法。
同步塊。
靜態同步。
2.協作(java中的線程間通信)
互斥有助于防止線程在共享數據時相互干擾。可以通過以下三種方式實現:
1.通過使用同步方法
2.通過使用同步塊
3.通過使用靜態同步
同步是圍繞稱為鎖或監視器的內部實體構建的。每個對象都有一個與之關聯的鎖。按照慣例,需要對對象字段進行一致訪問的線程必須在訪問對象之前獲取對象的鎖,然后在完成訪問時釋放鎖。
從 Java 5 開始,包 java.util.concurrent.locks 包含多個鎖實現。
在沒有同步的情況下理解問題
在這個例子中,沒有同步,所以輸出不一致。讓我們看看這個例子:
TestSynchronization1.java
class Table{
void printTable(int n){//method not synchronized
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
class TestSynchronization1{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
輸出:
5
100
10
200
15
300
20
400
25
500
如果您將任何方法聲明為同步,則稱為同步方法。
同步方法用于為任何共享資源鎖定對象。
當線程調用同步方法時,它會自動獲取該對象的鎖,并在線程完成其任務時釋放它。
TestSynchronization2.java
//example of java synchronized method
class Table{
synchronized void printTable(int n){//synchronized method
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
public class TestSynchronization2{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
輸出:
5
10
15
20
25
100
200
300
400
500
在這個程序中,我們使用匿名類創建了兩個線程,因此需要較少的編碼。
TestSynchronization3.java
//Program of synchronized method by using annonymous class
class Table{
synchronized void printTable(int n){//synchronized method
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}
public class TestSynchronization3{
public static void main(String args[]){
final Table obj = new Table();//only one object
Thread t1=new Thread(){
public void run(){
obj.printTable(5);
}
};
Thread t2=new Thread(){
public void run(){
obj.printTable(100);
}
};
t1.start();
t2.start();
}
}
輸出:
5
10
15
20
25
100
200
300
400
500
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習