您的位置:首页 > 编程语言 > Java开发

java中关于锁的关键字

2015-09-05 21:33 555 查看
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 : 0
thread5 : 1
thread3 : 2
thread2 : 2
thread6 : 4
thread7 : 5
thread9 : 5
thread8 : 7
thread4 : 8
thread1 : 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 : 0
thread2 : 1
thread3 : 2
thread1 : 3
thread6 : 4
thread8 : 5
thread9 : 6
thread7 : 7
thread5 : 8
thread4 : 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 : 0
thread1 : 0
thread2 : 0
thread4 : 3
thread5 : 3
thread6 : 4
thread3 : 6
thread7 : 6
thread8 : 6
thread9 : 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 : 0
thread1 : 0
thread3 : 2
thread5 : 2
thread2 : 4
thread7 : 5
thread6 : 6
thread9 : 7
thread4 : 8
thread8 : 8
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: