java中锁的使用

1、悲观锁
package concurrent;

import java.util.concurrent.TimeUnit;


public class SynchroniedTest {

    public static int a=0;
    
    public synchronized static int getAIncreament(){
        SynchroniedTest.a=SynchroniedTest.a+1;
        return SynchroniedTest.a;
    }
    /**
     * 
     * @param args
     */
    public static void main(String[] args) {
        new Thread(new Runnable(){

            @Override
            public void run() {
                long aa=0;
                while(true){
                 aa=SynchroniedTest.getAIncreament(); 
                 try {
                    TimeUnit.MILLISECONDS.sleep(1000);
                } catch (InterruptedException e) {
                }
                 System.out.println(aa+"  "+Thread.currentThread().getName());
                }
            }
        }).start();
        
        new Thread(new Runnable(){

            @Override
            public void run() {
                long aa=0;
                while(true){
                    aa=SynchroniedTest.getAIncreament(); 
                    try {
                        TimeUnit.MILLISECONDS.sleep(1000);
                    } catch (InterruptedException e) {
                    }
                 System.out.println(aa+"  "+Thread.currentThread().getName());
                }
            }
        }).start();
    }

}
2、乐观锁

package concurrent;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;

public class AtomicLongTest {

    /**
     * 
     * @param args
     */
    public static void main(String[] args) {
        AtomicLong number=new AtomicLong();
        AtomicInteger integer=new AtomicInteger();
        LongAdder longAdder=new LongAdder();
            new Thread(new Runnable(){

                @Override
                public void run() {
                    long aa=0;
                    while(number.get()<100){
                     aa=number.getAndIncrement(); 
                     System.out.println(aa+"  "+Thread.currentThread().getName());
                    }
                }
            }).start();
            
            new Thread(new Runnable(){

                @Override
                public void run() {
                    long aa=0;
                    while(number.get()<100){
                      aa=number.getAndIncrement();
                     System.out.println(aa+"  "+Thread.currentThread().getName());
                    }
                }
            }).start();
            
//            new Thread(new Runnable(){
//
//                @Override
//                public void run() {
//                    long aa=0;
//                    while(aa<=100){
//                     aa=number.decrementAndGet(); 
//                     try {
//                         TimeUnit.MILLISECONDS.sleep(1000);
//                     } catch (InterruptedException e) {
//                     }
//                     System.out.println(aa+"  "+Thread.currentThread().getName());
//                    }
//                }
//            }).start();
            System.out.println(number.accumulateAndGet(1000, Math::max));
    }

}

3、1.6中java。util。concurrent包中更加细力度的读写锁


package concurrent;


import java.util.Random;
import java.util.concurrent.locks.ReentrantReadWriteLock;


public class ReentrantReadWriteTest {


    public static void main(String[] args) {
         Queue3 q3 = new Queue3();
        for(int i=0;i<3;i++)
        {
            new Thread(){
                public void run(){
                    while(true){
                        q3.get();                        
                    }
                }
                
            }.start();
        }
        for(int i=0;i<3;i++)
        {        
            new Thread(){
                public void run(){
                    while(true){
                        q3.put(new Random().nextInt(10000));
                    }
                }            
                
            }.start();    
        }
    }
    
    static class Queue3{
        private Object data = null;//共享数据,只能有一个线程能写该数据,但可以有多个线程同时读该数据。
        private ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
        public void get(){
            rwl.readLock().lock();//上读锁,其他线程只能读不能写
            System.out.println(Thread.currentThread().getName() + " be ready to read data!");
            try {
                Thread.sleep((long)(Math.random()*1000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "have read data :" + data);        
            rwl.readLock().unlock(); //释放读锁,最好放在finnaly里面
        }
        
        public void put(Object data){


            rwl.writeLock().lock();//上写锁,不允许其他线程读也不允许写
            System.out.println(Thread.currentThread().getName() + " be ready to write data!");                    
            try {
                Thread.sleep((long)(Math.random()*1000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            this.data = data;        
            System.out.println(Thread.currentThread().getName() + " have write data: " + data);                    
            
            rwl.writeLock().unlock();//释放写锁    
        }
    }


}
4、java1.8中新增的StampedLock
package concurrent;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.StampedLock;

public class StampedLocKTest {

    private static int a = 0;

    public static int getA() {
        StampedLock lock = new StampedLock();
        // 乐观锁,获取当前数据版本
        long stamp = lock.tryOptimisticRead();
//        StampedLocKTest.a = StampedLocKTest.a + 1;
        // 检查数据版本
        if (!lock.validate(stamp)) {
//             数据版本发生变化(有写入操作),转悲观读锁
            lock.readLock();
            try {
                // 重新赋值
                StampedLocKTest.a = StampedLocKTest.a + 1;
            } finally {
                // 释放悲观锁
                lock.unlock(stamp);
            }
        }
        return StampedLocKTest.a;
    }

    public static void main(String[] args) {
        new Thread(new Runnable() {

            @Override
            public void run() {
                long aa = 0;
                while (true) {
                    aa = StampedLocKTest.getA();
                    System.out.println(aa + "  " + Thread.currentThread().getName());
                    try {
                        TimeUnit.MILLISECONDS.sleep(1000);
                    } catch (InterruptedException e) {
                    }
                }
            }
        }).start();

        new Thread(new Runnable() {

            @Override
            public void run() {
                long aa = 0;
                while (true) {
                    aa = StampedLocKTest.getA();
                    System.out.println(aa + "  " + Thread.currentThread().getName());
                    try {
                        TimeUnit.MILLISECONDS.sleep(2000);
                    } catch (InterruptedException e) {
                    }
                }
            }
        }).start();

        new Thread(new Runnable() {

            @Override
            public void run() {
                long aa = 0;
                while (true) {
                    aa = StampedLocKTest.getA();
                    System.out.println(aa + "  " + Thread.currentThread().getName());
                    try {
                        TimeUnit.MILLISECONDS.sleep(10000);
                    } catch (InterruptedException e) {
                    }
                }
            }
        }).start();
    }

}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值