歡迎您光臨本站 註冊首頁

Java使用synchronized實現互斥鎖功能示例

←手機掃碼閱讀     e36605 @ 2020-05-14 , reply:0

代碼

package per.thread; import java.io.IOException; public class Test {
private int i = 0;
private Object object = new Object();
 public static void main(String[] args) throws IOException {
 Test test = new Test(); Test.MyThread thread1 = test.new MyThread();
  Test.MyThread thread2 = test.new MyThread(); thread1.start();
  thread2.start(); }
class MyThread extends Thread{ @Override public void run() {
synchronized (object) { i++; System.out.println("i:"+i); try {
System.out.println("線程"+Thread.currentThread().getName()+"進入睡眠狀態");
 Thread.currentThread().sleep(10000); } catch (InterruptedException e) {
 // TODO: handle exception
  }
 System.out.println("線程"+Thread.currentThread().getName()+"睡眠結束");
 i++; System.out.println("i:"+i); } } } }


實現

i:1 
線程Thread-0進入睡眠狀態 
線程Thread-0睡眠結束 
i:2 
i:3 
線程Thread-1進入睡眠狀態 
線程Thread-1睡眠結束 
i:4

分析

在thread1休眠之後,thread2沒有立即執行,因為給object加了synchronized。



[e36605 ] Java使用synchronized實現互斥鎖功能示例已經有241次圍觀

http://coctec.com/docs/java/show-post-234538.html