线程交替打印

synchronized实现

public class App {
    public static Object object = new Object();
    public static boolean flag = false;

    public static void main(String[] args) {

        new Thread(() -> {
            String str[] = {"a", "b", "c", "d"};
            int index = 0;
            while (index < str.length) {
                synchronized (object) {
                    try {
                        if (flag) object.wait();
                        System.out.println(str[index++]);
                        flag = true;
                        object.notify();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

        new Thread(() -> {
            int ints[] = {1, 2, 3, 4,};
            int index = 0;
            while (index < ints.length) {
                synchronized (object) {
                    try {
                        if (!flag) object.wait();
                        System.out.println(ints[index++]);
                        flag = false;
                        object.notify();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }
}

volatile实现

/**
 * Hello world!
 * 线程通信
 * volatile实现
 * 单线程修改volatile数据,不会造成安全问题
 */
public class App2 {
    public static volatile boolean flag = true;

    public static void main(String[] args) {

        new Thread(() -> {
            String str[] = {"a", "b", "c", "d"};
            int index = 0;
            while (index < str.length) {
                if (!flag) {
                    System.out.println(str[index++]);
                    flag = true;
                }
            }
        }).start();

        new Thread(() -> {
            int ints[] = {1, 2, 3, 4,};
            int index = 0;
            while (index < ints.length) {
                if (flag) {
                    System.out.println(ints[index++]);
                    flag = false;
                }
            }
        }).start();

    }
}

lock实现

/**
 * Hello world!
 * 线程通信
 * lock+实现
 */
public class App3 {
    public static boolean flag = true;
    public static ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) {
        new Thread(() -> {
            String str[] = {"a", "b", "c", "d"};
            int index = 0;
            while (index < str.length) {
                lock.lock();
                if (!flag) {
                    System.out.println(str[index++]);
                    flag = true;
                }
                lock.unlock();
            }

        }
        ).start();

        new Thread(() -> {
            int ints[] = {1, 2, 3, 4,};
            int index = 0;
            while (index < ints.length) {
                lock.lock();
                if (flag) {
                    System.out.println(ints[index++]);
                    flag = false;
                }
                lock.unlock();
            }
        }).start();

    }
}

lock+condition实现

public class App5 {
    public static  boolean flag = true;
    public static ReentrantLock lock = new ReentrantLock();
    static Condition condition = lock.newCondition();

    public static void main(String[] args) {

        new Thread(() -> {
            String str[] = {"a", "b", "c", "d"};
            int index = 0;
            try {
                while (index < str.length) {
                    lock.lock();
                    if (flag) {
                        condition.await();
                    }
                    System.out.println(str[index++]);
                    flag = true;
                    condition.signal();
                    lock.unlock();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        ).start();

        new Thread(() -> {
            int ints[] = {1, 2, 3, 4,};
            int index = 0;
            try {
                while (index < ints.length) {
                    lock.lock();
                    if (!flag) {
                        condition.await();
                    }
                    System.out.println(ints[index++]);
                    flag = false;
                    condition.signal();
                    lock.unlock();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

    }
}

Unsafe加锁抢占式实现,支持可重入,死锁检测

/**
 * Hello world!
 * 线程通信
 * unsafe实现,抢占式,支持可重入,和死锁恢复
 */
public class App4 {

    private static Unsafe unsafe = null;
    private static long valueOffset;
    private volatile String threadName = "";

    static {
        try {

            Field getUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
            getUnsafe.setAccessible(true);
            unsafe = (Unsafe) getUnsafe.get(null);
        } catch (Exception ex) {
            throw new Error(ex);
        }
    }


    public static void main(String[] args) throws NoSuchFieldException {
        valueOffset = unsafe.objectFieldOffset
                (App4.class.getDeclaredField("threadName"));
        App4 app4 = new App4();

        //记录所有正在执行的线程
        ConcurrentHashMap<String, Thread> threadMap = new ConcurrentHashMap<String, Thread>();
        Thread aa = threadMap.get("aa");
        Thread thread = new Thread(new Runnable() {
            //记录重入次数
            ThreadLocal<Integer> t = new ThreadLocal<>();

            @Override
            public void run() {
                String str[] = {"a", "b", "c", "d"};
                int index = 0;

                //设置默认重入次数
                Optional<Integer> integer = Optional.ofNullable(t.get());
                if (!integer.isPresent()) {
                    t.set(0);
                }
                //注册当前线程
                Thread thread1 = Thread.currentThread();
                threadMap.put(thread1.getName(), thread1);
                try {
                    while (index < str.length) {
                        if (unsafe.compareAndSwapObject(app4, valueOffset, "", "Thread-01")) {
                            t.set(t.get() + 1);
                            System.out.println(str[index++]);
                            //int i=1/0; 测试死锁
                            if (t.get() == 1) {
                                unsafe.compareAndSwapObject(app4, valueOffset, "Thread-01", "");
                                t.set(0);
                            }
                        }
                    }

                } catch (Exception e) {
                } finally {
                    threadMap.remove(thread1.getName());
                }
            }
        }, "Thread-01"
        );

        Thread thread1 = new Thread(() -> {
            int ints[] = {1, 2, 3, 4,};
            int index = 0;
            Thread thread2 = Thread.currentThread();
            threadMap.put(thread2.getName(), thread2);
            while (index < ints.length) {
                if (unsafe.compareAndSwapObject(app4, valueOffset, "", "Thread-02")) {
                    System.out.println(ints[index++]);
                    unsafe.compareAndSwapObject(app4, valueOffset, "Thread-02", "");
                }

            }
            threadMap.remove(thread2.getName());
        }, "Thread-02");
        thread.start();
        thread1.start();

        //防止死锁
        new Thread(() -> {
            while (!threadMap.isEmpty()) {
                String threadName = (String) unsafe.getObject(app4, valueOffset);
                Thread thread2 = threadMap.get(threadName);
                Optional.ofNullable(thread2).ifPresent(s -> {
                    if (!thread2.isAlive()) {
                        unsafe.putObject(app4, valueOffset, "");
                    }
                });
            }
        }).start();

    }


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值