執行緒同步的緣由和方法

2021-08-30 14:34:32 字數 1338 閱讀 7669

我們知道,使用runnable方式實現執行緒可以實現資源共享,但是,依然存在問題,看下面的**:

//需要同步的原因 class mythread implements runnable catch(interruptedexception e){} system.out.println(thread.currentthread().getname()+"賣票: "+ticket--); } } } } public class syncdemo01 }

當有延遲的時候,可能會造成資源的共享出錯。所以我們需要使用同步,以解決此問題。實現同步也有兩種方式,使用synchronized**塊和使用synchronized方法。

首先,看第一種方法,使用synchronized**塊:

//使用synchronized,同步**塊進行同步 class mythread implements runnable catch(interruptedexception e){} system.out.println(thread.currentthread().getname()+"賣票: "+ticket--); } } } } } public class syncdemo02 }

通過執行可以看到,可以很好的解決問題。同時通過多次執行也可以看到程序間的搶占和切換。

再來看第二種實現方式,使用synchronized方法:

//使用synchronized方法進行同步 class mythread implements runnable } public synchronized void fun()catch(interruptedexception e){} system.out.println(thread.currentthread().getname()+"賣票: "+ticket--); } } } public class syncdemo03 }

通過執行可以發現,此種方式也可以解決問題。當做到這裡的時候,我有了個疑問,使用synchronized方法進行同步,那麼run方法也是方法,可不可以將run方法設為同步方法呢。為解決此問題,進行下面的嘗試:

//嘗試將run方法設為同步方法 class mythread implements runnable catch(interruptedexception e){} system.out.println(thread.currentthread().getname()+"賣票: "+ticket--); } } } } public class syncdemo04 }

通過執行,發現依然可以成功,那麼這樣做是否有問題呢?synchronized**塊和synchronized方法兩種不同的實現同步的方式有何區別呢?以上的**都是通過實現runnable介面實現的執行緒,通過繼承thread實現的執行緒可否進行同步呢?

執行緒同步的緣由和方法

我們知道,使用runnable方式實現執行緒可以實現資源共享,但是,依然存在問題,看下面的 需要同步的原因 class mythread implements runnable catch interruptedexception e system.out.println thread.curren...

多執行緒方法和同步方法

1.多執行緒有幾種實現方法?答 兩種方法,分別是繼承thread類和實現runnable藉口。2.同步有幾種實現方法?答 兩種。分別是synchronized,wait 與notify.3.stop 和suspend 方法為何不推薦使用?答 反對使用stop 方法,因為它不安全。它會解除由執行緒獲取...

執行緒同步的方法

一 執行緒同步的方法 1 reentrantlock a 加鎖 reentrantlock lock new reentrantlock finally b condition variable condition fund finally 2 synchronized a 加鎖 synchroni...