JAVA_THREAD_DEMO

线程死锁:

package com.thread;

public class TestDeadLock extends Thread {  
    static Object o1 = new Object(), o2 = new Object();  
    int flag = 0;  
    public void run() {  
        if(flag == 0){  
            synchronized (o1) {  
                System.out.println("tdl1锁定了o1");  
                try {  
                    Thread.sleep(500);  
                } catch (InterruptedException e) {  
                    e.printStackTrace();  
                }  
                synchronized (o2){  
                    System.out.println("tdl1---success");  
                }  
            }  
        }  
        if(flag == 1){  
            synchronized (o2) {  
                System.out.println("tdl2锁定了o2");  
                try {  
                	Thread.sleep(500);  
                } catch (InterruptedException e) {  
                    e.printStackTrace();  
                }  
                synchronized (o1){  
                    System.out.println("tdl2---success");  
                }  
            }  
        }  
    }  
    public static void main(String[] args) {  
        TestDeadLock tdl1 = new TestDeadLock();  
        TestDeadLock tdl2 = new TestDeadLock();  
        tdl1.flag = 0;  
        tdl2.flag = 1;  
        tdl1.start();  
        tdl2.start();  
    }  
}

生产消费:

package com.thread;

public class ProducerCustomer {  
    public static void main(String[] args) {  
        SyncStack ss = new SyncStack();  
        Producer pr = new Producer(ss);  
        Customer cr = new Customer(ss);  
        Thread pr1 = new Thread(pr);  
        Thread pr2 = new Thread(pr);  
        Thread cr1 = new Thread(cr);  
        Thread cr2 = new Thread(cr);  
        pr1.setName("---生产者P1");  
        pr2.setName("---生产者p2");  
        cr1.setName("消费者c1");  
        cr2.setName("消费者c2");  
        pr1.start();  
        pr2.start();  
        cr1.start();  
        cr2.start();  
    }  
}  
/**
 * 生产消费对象
 */
class Product{  
    private int id;   
    public Product(int id) {  
        this.id = id;  
    }  
    public String toString() {  
        return "Product的编号: " + id;  
    }  
}  
/**
 * 存储产品的仓库  
 */
class SyncStack{  
    //索引,其大小是库存量  
    int index = 0;  
    Product[] arrPd = new Product[10];  
    //生产者生产  
    public synchronized void push(Product pd){  
        //如果仓库满了  
        while(index == arrPd.length){  
            try {  
                this.wait();  
            } catch (InterruptedException e) {  
                e.printStackTrace();  
            }  
        }  
        this.notifyAll();  
        arrPd[index] = pd;  
        index ++;  
    }  
    //消费者消费  
    public synchronized Product pop(){  
        //仓库没有存货  
        while(index == 0){  
            try {  
                this.wait();  
            } catch (InterruptedException e) {  
                e.printStackTrace();  
            }  
        }  
        this.notifyAll();  
        return arrPd[--index];  
    }  
}  
class Producer implements Runnable{  
    SyncStack ss = null;  
    public Producer(SyncStack ss){  
        this.ss = ss;  
    }  
    public void run() {  
        for(int i = 1; i <= 10; i++){  
            Product pd = new Product(i);  
            ss.push(pd);  
            System.out.println(Thread.currentThread().getName()+"生产了"+pd.toString());  
            try {  
                //随机睡眠一个时间  
                Thread.sleep((int)Math.random()*100);  
            } catch (InterruptedException e) {  
                e.printStackTrace();  
            }  
        }  
    }  
}  
class Customer implements Runnable{  
    SyncStack ss = null;  
    public Customer(SyncStack ss){  
        this.ss = ss;  
    }  
    public void run() {  
        for(int i = 1; i <= 10; i++){  
            Product pd = ss.pop();  
            System.out.println(Thread.currentThread().getName()+"消费了"+pd.toString());  
            try {  
                //随机睡眠一个时间  
                Thread.sleep((int)Math.random()*1000);  
            } catch (InterruptedException e) {  
                e.printStackTrace();  
            }  
        }  
    }  
}  


以下是一个使用看门狗为Redis分布式锁续约的Java demo: ```java import redis.clients.jedis.Jedis; import redis.clients.jedis.params.SetParams; public class RedisLock { private Jedis jedis; private String key; private int timeout; private Thread watchDogThread; private boolean locked; public RedisLock(Jedis jedis, String key, int timeout) { this.jedis = jedis; this.key = key; this.timeout = timeout; this.watchDogThread = null; this.locked = false; } public void acquire() throws InterruptedException { /* * 获取分布式锁,如果获取成功,则启动看门狗线程续约 */ while (!locked) { // 尝试获取锁 long lockValue = System.currentTimeMillis() + timeout + 1; SetParams params = SetParams.setParams().nx().ex(timeout); String result = jedis.set(key, String.valueOf(lockValue), params); if ("OK".equals(result)) { // 获取锁成功,启动看门狗线程续约 locked = true; watchDogThread = new Thread(this::watchDog); watchDogThread.start(); } else { // 获取锁失败,等待一段时间后重试 Thread.sleep(100); } } } public void release() { /* * 释放分布式锁,同时停止看门狗线程 */ if (locked) { locked = false; jedis.del(key); watchDogThread.interrupt(); } } public void renew() { /* * 续约,更新锁的过期时间 */ if (locked) { long lockValue = System.currentTimeMillis() + timeout + 1; jedis.set(key, String.valueOf(lockValue), "XX", "EX", timeout); } } public void watchDog() { /* * 看门狗线程,定期续约 */ while (locked) { try { Thread.sleep(timeout / 2); renew(); } catch (InterruptedException e) { // 线程被中断,停止看门狗线程 break; } } } } ``` 在这个demo中,我们定义了一个RedisLock类,其中包含了获取锁、释放锁、续约等方法。在获取锁的时候,如果获取成功,则会启动一个看门狗线程,在锁的过期时间内定期向Redis发送续约请求。在释放锁的时候,会停止看门狗线程。在程序运行过程中,我们创建了一个RedisLock对象,并使用该对象获取分布式锁,然后等待一段时间后释放锁。 需要注意的是,在Java中,我们使用了Lambda表达式来创建看门狗线程。如果你的Java版本不支持Lambda表达式,可以将watchDog方法写成一个普通的方法,然后创建一个新的类来实现Runnable接口。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值