[英]My program has hang and I dont know how to fix it for now
这是我程序的一部分。 我坚信此类是我的代码被挂起的地方。 我在java
使用死锁线程,遇到了困难。
所以我不想显示我的整个代码,但这只是一个示例。 有人可以告诉我为什么挂吗? 这种僵局使我感到困惑。
public class gameEnemyRelease {
private static Object enemy1 = new Object();
public static Object enemy2= new Object();
public static void main(String args[]) {
player1 p1 = new player1();
player2 p2 = new player2();
p1.start();
p2.start();
}
private static class player1 extends Thread {
public void run() {
synchronized (enemy1) {
System.out.println("Start Launch");
try { Thread.sleep(10); }
catch (InterruptedException e) {}
System.out.println("Waiting for enemy 2 to launch...");
synchronized (enemy2) {
System.out.println("Shot");
}
}
}
}
private static class player2 extends Thread {
public void run() {
synchronized (enemy2) {
System.out.println("...");
try { Thread.sleep(10); }
catch (InterruptedException e) {}
System.out.println("");
synchronized (enemy1) {
System.out.println("");
}
}
}
}
}
您的程序正在挂起,可能是因为没有一个线程继续运行并等待彼此释放锁。 因此,您可以尝试更改此方法; 试试下面的代码:
private static class player2 extends Thread {
public void run() {
synchronized (enemy1) {
System.out.println("...");
try { Thread.sleep(10); }
catch (InterruptedException e) {}
System.out.println("");
synchronized (enemy2) {
System.out.println("");
}
}
考虑以下代码路径:
您需要解决并可能从一开始就锁定两个敌人。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.