【重点:Lock】把sychronized改为lock的方法

本文通过两个示例对比了Java中使用synchronized关键字与ReentrantLock实现线程同步的方法。演示了如何保护共享资源免受多个线程同时访问导致的数据不一致问题。

sychronized

[java]   view plain  copy
 print ?
  1. package com.xiaozhi.threadlocal2;  
  2.   
  3.   
  4. public class Test {  
  5.   
  6.     public static void main(String[] args) {  
  7.         MyRun myRun=new MyRun();  
  8.         for(int i=0;i<10;i++)  
  9.             new Thread(myRun).start();  
  10.     }  
  11. }  
  12.   
  13. class MyRun implements Runnable {  
  14.     int num = 10;  
  15.     public synchronized void run() {  
  16.             while(num > 0) {  
  17.                 try {Thread.sleep(1000);} catch (InterruptedException e) {}  
  18.                 num--;  
  19.                 System.out.println(num);  
  20.             }  
  21.           
  22.     }  
  23. }  

lock

[java]   view plain  copy
 print ?
  1. package com.xiaozhi.threadlocal2;  
  2.   
  3. import java.util.concurrent.locks.Lock;  
  4. import java.util.concurrent.locks.ReentrantLock;  
  5.   
  6. public class Test {  
  7.   
  8.     public static void main(String[] args) {  
  9.         MyRun myRun=new MyRun();  
  10.         for(int i=0;i<10;i++)  
  11.             new Thread(myRun).start();  
  12.     }  
  13. }  
  14.   
  15. class MyRun implements Runnable {  
  16.     int num = 10;  
  17.     Lock lock = new ReentrantLock();  
  18.     public /*synchronized*/ void run() {  
  19.             lock.lock();  
  20.             try {  
  21.                 while(num > 0) {  
  22.                     try {Thread.sleep(1000);} catch (InterruptedException e) {}  
  23.                     num--;  
  24.                     System.out.println(num);  
  25.                 }  
  26.             } catch (Exception e) {  
  27.                 e.printStackTrace();  
  28.             }finally{  
  29.                 lock.unlock();  
  30.             }  
  31.               
  32.           
  33.     }  
  34. }  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值