标签:管道流 ide get trace over nbsp package string while
synchronized死锁
package com.thread.demo.deadlock; public class DeadLock { private static Object lock1 = new Object(); private static Object lock2 = new Object(); public static void main(String[] args) { // 创建线程1 new Thread(new Runnable() { @Override public void run() { while (true) { synchronized (lock1) { System.out.println(Thread.currentThread().getName() + "获取到lock1这把锁"); System.out.println(Thread.currentThread().getName() + "等待lock2锁.........."); synchronized (lock2) { System.out.println(Thread.currentThread().getName() + "获取到lock2这把锁"); } } } } }, "A线程").start(); // 创建的线程2 new Thread(new Runnable() { @Override public void run() { while (true) { synchronized (lock2) { System.out.println(Thread.currentThread().getName() + "获取到lock2这把锁"); System.out.println(Thread.currentThread().getName() + "等待lock1锁.........."); synchronized (lock1) { System.out.println(Thread.currentThread().getName() + "获取到lock1这把锁"); } } } } }, "B线程").start(); } }
ReentrantLock死锁
package com.thread.demo.deadlock; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class ReentrantDeadLock { private static Lock lock = new ReentrantLock(); public static void main(String[] args) { new Thread(new MyRunnable(lock), "一线程").start(); new Thread(new MyRunnable(lock), "二线程").start(); } } class MyRunnable implements Runnable { private Lock lock; private static int count = 0; public MyRunnable(Lock lock) { this.lock = lock; } @Override public void run() { lock.lock(); try { for (int i = 0; i < 100000000; i++) { count++; if (i == 100000) { throw new RuntimeException(); } } System.out.println(Thread.currentThread().getName() + ":count=" + count); } catch(Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } }
死锁,线程协作(同步,阻塞队列,Condition,管道流)
标签:管道流 ide get trace over nbsp package string while
原文地址:https://www.cnblogs.com/sunBinary/p/10589030.html