线程 死锁解决办法
线程 死锁
public class 死锁Test implements Runnable
{
public static Object S1 = new Object();
public static Object S2 = new Object();
public void run() {
if(Thread.currentThread().getName().equals("PH1")) {
synchronized(S1) {
System.out.println("线程1锁定S1");
try {
Thread.sleep(1000);
}catch(Exception ex) {
}
synchronized(S2){
System.out.println("线程1锁定S2");
}
}
}else{
synchronized(S2) {
System.out.println("线程2锁定S2");
synchronized(S1) {
System.out.println("线程2锁定S2");
}
}
}
}
public static void main(String[] args) {
Thread t1 = new Thread(new 死锁Test(),"PH1");
Thread t2 = new Thread(new 死锁Test(),"PH2");
t1.start();
t2.start();
}
}
为什么这个程序不能 死锁 怎么稍微修改一下就出现死锁 求大牛指导 谢谢
------解决思路----------------------
------解决思路----------------------
public class 死锁Test implements Runnable
{
public static Object S1 = new Object();
public static Object S2 = new Object();
public void run() {
if(Thread.currentThread().getName().equals("PH1")) {
synchronized(S1) {
System.out.println("线程1锁定S1");
try {
Thread.sleep(1000);
}catch(Exception ex) {
}
synchronized(S2){
System.out.println("线程1锁定S2");
}
}
}else{
synchronized(S2) {
System.out.println("线程2锁定S2");
synchronized(S1) {
System.out.println("线程2锁定S2");
}
}
}
}
public static void main(String[] args) {
Thread t1 = new Thread(new 死锁Test(),"PH1");
Thread t2 = new Thread(new 死锁Test(),"PH2");
t1.start();
t2.start();
}
}
为什么这个程序不能 死锁 怎么稍微修改一下就出现死锁 求大牛指导 谢谢
------解决思路----------------------
public class LockTest implements Runnable
{
public LockTest(Object S1,Object S2){
this.S1 = S1;this.S2 = S2;
}
public Object S1;
public Object S2;
public void run() {
if(Thread.currentThread().getName().equals("PH1")) {
synchronized(S1) {
System.out.println("线程1锁定S1");
try {
Thread.sleep(1000);
}catch(Exception ex) {
}
synchronized(S2){
System.out.println("线程1锁定S2");
}
}
}else{
synchronized(S2) {
System.out.println("线程2锁定S2");
synchronized(S1) {
System.out.println("线程2锁定S2");
}
}
}
}
public static void main(String[] args) {
Object S1 = new Object();Object S2 = new Object();
Thread t1 = new Thread(new LockTest(S1,S2),"PH1");
Thread t2 = new Thread(new LockTest(S1,S2),"PH2");
t1.start();
t2.start();
}
}
------解决思路----------------------
public class 死锁Test implements Runnable
{
public static Object S1 = new Object();
public static Object S2 = new Object();
public void run() {
if(Thread.currentThread().getName().equals("PH1")) {
synchronized(S1) {
System.out.println("线程1锁定S1");
try {
Thread.sleep(1000);
}catch(Exception ex) {
}
synchronized(S2){
System.out.println("线程1锁定S2");
}
}
}else{
synchronized(S2) {
System.out.println("线程2锁定S2");
synchronized(S1) {
System.out.println("线程2锁定S2");
}
}
}
}
public static void main(String[] args) {
死锁Test st=new 死锁Test();
Thread t1 = new Thread(st,"PH1");
Thread t2 = new Thread(st,"PH2");
t1.start();
t2.start();
}
}