我这个java程序,怎么才能实现死锁?
importjava.io.*;importjava.util.*;publicclassLock{publicstaticvoidmain(String[]args){...
import java.io.*;
import java.util.*;
public class Lock
{
public static void main(String[] args)
{
runner r1 = new runner(1);
runner r2 = new runner(0);
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t1.start();
t2.start();
System.out.println("first print");
}
}
class runner implements Runnable
{
private int i = 0;
runner(int n) {i = n;}
Object o1 = new Object(),o2 = new Object();
@Override
public void run() {
// TODO Auto-generated method stub
if (i == 0)
{
synchronized (o1) {
try{
Thread.sleep(500);
}catch (InterruptedException e) {}
}
synchronized (o2) {
{
System.out.println("i == 0如果不死锁就会输出这行");
}
}
}
if (i == 1)
{
synchronized (o2) {
{
try{
Thread.sleep(500);
}catch (InterruptedException e) {}
}
}
synchronized (o1) {
System.out.println("i == 1如果不死锁就会输出这行");
}
}
}
} 展开
import java.util.*;
public class Lock
{
public static void main(String[] args)
{
runner r1 = new runner(1);
runner r2 = new runner(0);
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t1.start();
t2.start();
System.out.println("first print");
}
}
class runner implements Runnable
{
private int i = 0;
runner(int n) {i = n;}
Object o1 = new Object(),o2 = new Object();
@Override
public void run() {
// TODO Auto-generated method stub
if (i == 0)
{
synchronized (o1) {
try{
Thread.sleep(500);
}catch (InterruptedException e) {}
}
synchronized (o2) {
{
System.out.println("i == 0如果不死锁就会输出这行");
}
}
}
if (i == 1)
{
synchronized (o2) {
{
try{
Thread.sleep(500);
}catch (InterruptedException e) {}
}
}
synchronized (o1) {
System.out.println("i == 1如果不死锁就会输出这行");
}
}
}
} 展开
4个回答
2014-01-25
展开全部
你把o1,o2都定义成runner的内部变量,main中的r1,r2都是用的自己的内部变量,两个线程没有使用共享的公共变量。想尝试死锁,可以吧o1,o2 提出来在runner初始化给他传进去
展开全部
给o1改了值 传给runner2 互相锁上
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
不要作死,就不会死
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询