Detailed explanation of Java thread deadlock code
- 2021-12-11 07:20:44
- OfStack
/**
* @author hollis
*/
public class JStackDemo {
public static void main(String[] args) {
Thread t1 = new Thread(new DeadLockclass(true));// Establish 1 Threads
Thread t2 = new Thread(new DeadLockclass(false));// Create another 1 Threads
t1.start();// Start 1 Threads
t2.start();// Start another 1 Threads
}
}
class DeadLockclass implements Runnable {
public boolean falg;// Control thread
DeadLockclass(boolean falg) {
this.falg = falg;
}
public void run() {
/**
* If falg The value of is true Call the t1 Thread
*/
if (falg) {
while (true) {
synchronized (Suo.o1) {
System.out.println("o1 " + Thread.currentThread().getName());
synchronized (Suo.o2) {
System.out.println("o2 " + Thread.currentThread().getName());
}
}
}
}
/**
* If falg The value of is false Call the t2 Thread
*/
else {
while (true) {
synchronized (Suo.o2) {
System.out.println("o2 " + Thread.currentThread().getName());
synchronized (Suo.o1) {
System.out.println("o1 " + Thread.currentThread().getName());
}
}
}
}
}
}
class Suo {
static Object o1 = new Object();
static Object o2 = new Object();
}
import org.springframework.stereotype.Component;
@Component
public class SynchronizedTest {
private static final Object lockA = new Object();
private static final Object lockB = new Object();
/**
* ThreadA Get first lockA, After getting lockB
*/
private static class ThreadA extends java.lang.Thread {
@Override
public void run() {
// Get critical area A
synchronized (lockA) {
System.out.println("get lockA success");
// Simulate time-consuming operations
try {
Thread.currentThread().setName(" Thread A");
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Get critical area B
synchronized (lockB) {
System.out.println("get lockB success");
}
}
}
}
/**
* ThreadB Get first lockB, After getting lockA
*/
private static class ThreadB extends java.lang.Thread {
@Override
public void run() {
// Get critical area A
synchronized (lockB) {
System.out.println("get lockB success");
// Simulate time-consuming operations
try {
Thread.currentThread().setName(" Thread B");
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Get critical area B
synchronized (lockA) {
System.out.println("get lockA success");
}
}
}
}
static {
new ThreadA().start();
new ThreadB().start();
}
}
Summarize
This article is here, I hope to give you help, but also hope that you can pay more attention to this site more content!