欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

javaSE

程序员文章站 2024-01-20 21:33:28
...

java线程之死锁

package com.thread.dome;

/**
 * @ClassName:
 * @author: YDJ
 * @Date: 2019年11月3日 下午6:17:38
 * @description: 模拟死锁
 */

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();
	}
}

package com.thread.dome;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/** 
 * @ClassName: 
 * @author: YDJ
 * @Date: 2019年11月3日 下午7:58:29
 * @description: 
 */

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();
		}
		

	}

}