【Java并发】共享资源:Lock 、synchronized、Atomic、volatile、local storage线程本地存储

本文探讨了Java中处理共享资源的多种方式,包括synchronized、Lock、Atomic和volatile。解释了Brian’s Rule of Synchronization,强调在多线程环境下正确同步的重要性。文章分析了synchronized关键字的使用,以及Lock对象提供的灵活性。还提到了Atomic类用于原子性操作,volatile确保可见性,并讨论了Thread Local Storage以避免线程间冲突。
摘要由CSDN通过智能技术生成

Brian’s Rule of Synchronization——If you are writing a variable that might next be read by another thread, or reading a variable that might have last been written by another thread, you must use synchronization, and further, both the reader and the writer must synchronize using the same monitor lock.

Improperly accessing resources

import java.util.concurrent.*;
//this class is the share resources
abstract class IntGenerator{
   
    private volatile boolean canceled =false;
    public abstract int next();
//    allow this to be canceled
    public void canceled(){
    canceled=true;}
    public boolean isCanceled() {
   return canceled;}
}
public class ShareResource implements Runnable{
   
    private IntGenerator generator;
    private final int id;
    public ShareResource(IntGenerator g , int ident){
   
        generator=g;
        id=ident;
    }
    @Override
    public void run() {
   
        while (!generator.isCanceled()){
   
            int val=generator.next();
            if(val %2 !=0){
   
                System.out.println(Thread.currentThread().getName()+" "+val +" not even");
                generator.canceled();
            }
        }
    }

    public static void test(IntGenerator gp, int count){
   
        System.out.println("Press Control-c to exit");
        ExecutorService exec = Executors.newCachedThreadPool();
        for (int i = 0; i <count ; i++) {
   
             exec.execute(new ShareResource(gp,i));
        }
        exec.shutdown();
    }
    public static void test(IntGenerator gp){
   
        test(gp,4);
    }
    public static void main(String[] args) {
   
        ShareResource.test(new EventGenerator());

    }
}
class EventGenerator extends IntGenerator{
   
    private int currentEvenValue = 0;
    @Override
    public int next
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值