线程同步锁与读写锁

同步锁简单例子

 以卖票为例子

/**
 * 实现 线程同步锁
 */
public class Tick2 extends Thread{
    //设定票的库存为100
    static int tick =100;
    @Override
    public void run() {
        while (true){
            //同步锁,Tick2.class唯一
            synchronized (Tick2.class){
                if (tick>0){
                    try{
                        Thread.sleep(10);//睡眠,暴露问题
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    }
                    //线程名 + tick -1
                    System.out.println(getName() + "=" + tick--);
                }
                if (tick<=0) break;//退出死循环
            }
        }
    }
}

main 测试调用 

public static void main(String[] args) throws InterruptedException {
		Tick2 t1 = new Tick2();
		Tick2 t2 = new Tick2();
		Tick2 t3 = new Tick2();
		Tick2 t4 = new Tick2();
		t1.start();
		t2.start();
		t3.start();
		t4.start();
}

输出结果为:

Thread-0=100
Thread-3=99
Thread-3=98
Thread-3=97
Thread-3=96
Thread-3=95
Thread-3=94
Thread-3=93
Thread-3=92
Thread-3=91
Thread-3=90
Thread-3=89
Thread-3=88
Thread-3=87
Thread-3=86
Thread-3=85
Thread-3=84
Thread-2=83
Thread-2=82
Thread-2=81
Thread-1=80

可看出同步锁就是看那个线程抢占资源快了………………

读写锁 简单例子

以卖票为例子

/**
 * 实现 线程读写锁
 */
public class Tick3 implements Runnable{
    //票库存为100
    static int tick =100;
    //读写锁,全局唯一
    static ReentrantReadWriteLock lock = new ReentrantReadWriteLock(true);
    @Override
    public void run() {
        while (true){
            //操作共享资源前上锁
            lock.writeLock().lock();
            try {
                if (tick >0) {
                    try {
                        Thread.sleep(10);//睡眠,暴露问题
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    //线程名 + tick -1
                    System.out.println(Thread.currentThread().getName() + "=" + tick--);
                }
                if (tick <=0) break;//票存为0退出死循环
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                //手动释放锁,防止死锁,否则独占报错
                lock.writeLock().unlock();
            }
        }

    }
}

main 测试调用 

public static void main(String[] args) throws InterruptedException {
		Tick3 t = new Tick3();
		Thread t1 = new Thread(t);
		Thread t2 = new Thread(t);
		Thread t3 = new Thread(t);
		Thread t4 = new Thread(t);
		t1.start();
		t2.start();
		t3.start();
		t4.start();
}

输出结果为:

Thread-0=100
Thread-1=99
Thread-2=98
Thread-3=97
Thread-0=96
Thread-1=95
Thread-2=94
Thread-3=93
Thread-0=92
Thread-1=91
Thread-2=90
Thread-3=89

可看出读写锁是线程排队进行资源的操作………………

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值