java中关于锁的关键字

来源:互联网 发布:oracle数据库图标 编辑:程序博客网 时间:2024/05/10 13:14

java中关于锁的关键字有2个 , synchronized 和volatile。
synchronized 可以对方法和语句块进行修饰。从而实现同一时刻只有一个线程能够执行。
volatile可以对变量进行修饰。保证线程在每次使用变量的时候,都会读取变量修改后的最的值。
很多人都将volatile理解为和synchronized差不多的功能。然而,实际情况并不是这样。
volatile只能保证从公共内存将值复制到工作线程内存的值是最新的。并不能保证工作线程内的操作和操作完成之后将值回写到公共内存的时候是同步的。

package locktest;public class VolatileTest  implements Runnable{    public static Counter c = new Counter();    @Override      public void run() {          c.add();    }     public static void main(String[] args) {        // 同时启动10个线程,去进行i++计算,看看实际结果        VolatileTest vt = new VolatileTest();        for(int i = 0;i<10;i++)        {            Thread t = new Thread(vt,"thread"+i);            t.start();        }    }}

没有任何锁的实现

package locktest;public class Counter {    public volatile int count = 0;    public int add()    {        System.out.println(Thread.currentThread().getName() + " : "+count);          return count++;    }}thread0 : 0thread5 : 1thread3 : 2thread2 : 2thread6 : 4thread7 : 5thread9 : 5thread8 : 7thread4 : 8thread1 : 8

synchronized 的实现:

package locktest;public class Counter {    public  int count = 0;    public synchronized int add()    {        System.out.println(Thread.currentThread().getName() + " : "+count);          return count++;    }}thread0 : 0thread2 : 1thread3 : 2thread1 : 3thread6 : 4thread8 : 5thread9 : 6thread7 : 7thread5 : 8thread4 : 9

volatile的实现

package locktest;public class Counter {    public  int count = 0;    public synchronized int add()    {        System.out.println(Thread.currentThread().getName() + " : "+count);          return count++;    }}thread0 : 0thread1 : 0thread2 : 0thread4 : 3thread5 : 3thread6 : 4thread3 : 6thread7 : 6thread8 : 6thread9 : 8

网上说,除了synchronized 之外,还有ReentrantLock 类,也可以实现与synchronized 同样的功能。
java.util.concurrent.lock 中的 Lock允许把锁定的实现作为 Java 类,而不是作为语言的特性来实现。ReentrantLock 就是Lock的一个具体实现。
ReentrantLock 添加了类似轮询锁、定时锁等候和可中断锁等候的一些特性。

然而 , 我测试了一下 , ReentrantLock并没有什么卵用…在main方法里加ReentrantLock我也试了,这个是为什么,希望有看官能够解释下 , 我了解了之后也会把原因写上~

package locktest;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;public class Counter {    public  int count = 0;    public  int add()    {        Lock lock = new ReentrantLock();        lock.lock();        try {             System.out.println(Thread.currentThread().getName() + " : "+count);              return count++;        }        finally {          lock.unlock();         }    }}thread0 : 0thread1 : 0thread3 : 2thread5 : 2thread2 : 4thread7 : 5thread6 : 6thread9 : 7thread4 : 8thread8 : 8
0 0
原创粉丝点击