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();
}
}
}
推荐阅读
-
JavaSE---反射
-
Java IO 之ByteArrayInputStream & ByteArrayOutputStream 博客分类: 再学JavaSE javaioByteArrayInputStreamByteArrayOutputStream
-
JavaSE——链表集合 博客分类: java
-
JavaSE——数组集合 博客分类: java
-
JavaSE —— IO简介 博客分类: java
-
JavaSE—单例模式
-
Java泛型 博客分类: JavaSE Java
-
Java获取客户端真实IP地址 博客分类: JavaSE JavaJSP应用服务器浏览器Apache
-
Java泛型 博客分类: JavaSE Java
-
java基础学习一、搭建java编译环境 博客分类: JavaSe基础 java编程