同步锁简单例子
以卖票为例子
/**
* 实现 线程同步锁
*/
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
可看出读写锁是线程排队进行资源的操作………………