各位大大 我写了一个程序是测试线程的死锁 但是发现打印出的结果和实际有出入 以下是源代码
class MyThreadTest
{
public static void main(String[] args){
ThreadTest tt = new ThreadTest();
new Thread(tt).start();
new Thread(tt).start();
//new Thread(tt).start();
//new Thread(tt).start();
}
}class ThreadTest implements Runnable
{
int i = 100;
Object o = new Object();
public void run(){
while(true){
synchronized(o){
try{
Thread.sleep(10);
}catch(Exception e){
e.printStackTrace();
}
synchronized(this){
if(i>0){
System.out.println("同步块~~"+Thread.currentThread().getName()+" "+i);
i--;
}
}
} test();
}
}
public synchronized void test(){
synchronized(o){
if(i>0){
try{
Thread.sleep(10);
System.out.println("同步方法~~"+Thread.currentThread().getName()+" "+i);
i--;
}catch(Exception e){
e.printStackTrace();
}
}
}
}
}理论上来说应该直接就进入死锁了 什么也不会打印 但是实际上会有很多打印结果 而且多次执行发现发生死锁的位置都不相同 哪位大大能给解释一下啊
class MyThreadTest
{
public static void main(String[] args){
ThreadTest tt = new ThreadTest();
new Thread(tt).start();
new Thread(tt).start();
//new Thread(tt).start();
//new Thread(tt).start();
}
}class ThreadTest implements Runnable
{
int i = 100;
Object o = new Object();
public void run(){
while(true){
synchronized(o){
try{
Thread.sleep(10);
}catch(Exception e){
e.printStackTrace();
}
synchronized(this){
if(i>0){
System.out.println("同步块~~"+Thread.currentThread().getName()+" "+i);
i--;
}
}
} test();
}
}
public synchronized void test(){
synchronized(o){
if(i>0){
try{
Thread.sleep(10);
System.out.println("同步方法~~"+Thread.currentThread().getName()+" "+i);
i--;
}catch(Exception e){
e.printStackTrace();
}
}
}
}
}理论上来说应该直接就进入死锁了 什么也不会打印 但是实际上会有很多打印结果 而且多次执行发现发生死锁的位置都不相同 哪位大大能给解释一下啊
解决方案 »
- 读取excel文件的问题
- hibernate weblogic JDNI 配置找不到DataSource
- 利用jacob将Word转成PDF时候报错:Invoke of: SaveAs
- 如何用java程序实现上传文件到指定的URL地址
- 今天晚上小生总结的SSH,自己的见解,哥哥姐姐们来指点一下。
- 请教一下Myeclipse的Debug的时候那个ID指的是什么?
- 用Spring 1.2 的事务代理类解决事务提交问题 请高手指点 在线等!!!
- 请问哪儿能下载struts 1的源代码
- 经典问题
- 关于JBuilder6 生成EJB程序的问题
- windows下如何安装ruby 1.9.1二进制文件版
- !!!!!!!!!!~~~~求救~~~~~!!!!!!!!!
{
public static void main(String[] args){
ThreadTest tt = new ThreadTest();
new Thread(tt).start();
try{
Thread.sleep(1);
}catch(Exception e){
e.printStackTrace();
}
tt.b = true;
new Thread(tt).start();
//new Thread(tt).start();
//new Thread(tt).start();
}
}class ThreadTest implements Runnable
{
int i = 100;
boolean b = false;
Object o = new Object();
public void run(){
if(b==true){
test();
}else{
while(true){
synchronized(o){
try{
Thread.sleep(10);
}catch(Exception e){
e.printStackTrace();
}
synchronized(this){
if(i>0){
System.out.println("同步块~~"+Thread.currentThread().getName()+" "+i);
i--;
}
}
}
}
}
}
public synchronized void test(){
synchronized(o){
if(i>0){
try{
Thread.sleep(10);
System.out.println("同步方法~~"+Thread.currentThread().getName()+" "+i);
i--;
}catch(Exception e){
e.printStackTrace();
}
}
}
}
}