Java同步块
为避免多线程出现资源竞争现象发生,我们可采用将代码标记上同步代码块,如:
以下两种代码的效果是一样的
同步代码块使用synchronized关键字进行标记下文笔者将讲述同步代码块应用的示例分享
实例方法同步
public synchronized void add(int value){
this.count += value;
}
//在方法前面加上synchronized关键字后,则告诉JVM此方法是同步方法
//此方法将会同步对实例对象的方法上,禁止多线程并发访问此方法
静态方法同步
静态方法同步和实例方法同步方法的定义方式相同,使用synchronized关键字即可,如下所示:
public static synchronized void add(int value){
count += value;
}
//静态方法的同步定义在类的方法上
实例方法中的同步块
同步块的方式,可使锁的粒度更小,提高程序的性能,如下所示:
public void add(int value){
synchronized(this){
this.count += value;
}
}
例:以下两种代码的效果是一样的
public class MyClass {
public synchronized void log1(String msg1, String msg2){
log.writeln(msg1);
log.writeln(msg2);
}
public void log2(String msg1, String msg2){
synchronized(this){
log.writeln(msg1);
log.writeln(msg2);
}
}
}
静态方法中的同步块
public class MyClass {
public static synchronized void log1(String msg1, String msg2){
log.writeln(msg1);
log.writeln(msg2);
}
public static void log2(String msg1, String msg2){
synchronized(MyClass.class){
log.writeln(msg1);
log.writeln(msg2);
}
}
}
//采用以上的方式定义,则可避免共享资源同时被多个线程访问
例:
public class Counter{
long count = 0;
public synchronized void add(long value){
this.count += value;
}
}
public class CounterThread extends Thread{
protected Counter counter = null;
public CounterThread(Counter counter){
this.counter = counter;
}
public void run() {
for(int i=0; i<10; i++){
counter.add(i);
}
}
}
public class Example {
public static void main(String[] args){
Counter counter = new Counter();
Thread threadA = new CounterThread(counter);
Thread threadB = new CounterThread(counter);
threadA.start();
threadB.start();
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


