问题描述
- java 模拟线程死锁实验
-
我想两个线程一直在售票知道票卖光,但是用while()控制循环后出现
售票2进入共享区
当前没有车票可以出售!
售票2进入共享区
当前没有车票可以出售!
售票2进入共享区
.....
具体代码如下
package com;
public class SaleThread extends Thread{
private String name;
ShareResource shareresource;
public SaleThread(){}
public SaleThread(String threadname){ //初始化线程名称的构造函数
this.name=threadname;
}
public SaleThread(String threadname,ShareResource shareresource1){//初始化共享区和线程名称
this.name=threadname;
shareresource=shareresource1;}
public void run(){
//synchronized (shareresource){
while(shareresource.currentticket>=0){
if(this.shareresource.isAccessed()){
System.out.println(this.name+"进入共享区");
shareresource.changeAccess(); //禁止其他的线程进入共享区
//while(shareresource.currentticket>=0&&this.shareresource.isAccessed()){
if(shareresource.isEmpty()){
System.out.println("当前没有车票可以出售!");
shareresource.changeAccess(); //操作完毕退出共享区,其他线程可以进入
}else{
shareresource.currentticket--;
System.out.println(name+"正在售出一张车票,"+"还剩下"+shareresource.currentticket+"张票。");
shareresource.changeAccess(); //操作完毕退出共享区,其他线程可以进入
}
} //if 结束else{
try{
shareresource.wait(100); //共享区不能进入该线程等待100ms
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
//}
}
}
package com;public class ShareResource {
public int currentticket;
public boolean isaccessed=true;
public ShareResource(){}
public ShareResource(int ticketnum){ //初始化共享区里的车票数
this.currentticket=ticketnum;
}
public void setShareResource(int cticket){ //重置共享区里的车票数
this.currentticket=cticket;
}
public boolean isEmpty(){ //判断共享区是否为空
if(currentticket>0) return false;
return true;
}
public boolean isAccessed(){ //判断共享区能否进入
if(isaccessed) return true;
else return false;
}
public void changeAccess(){ //改变共享区状态
this.isaccessed=!isaccessed;
}
public static void main(String[] args){
ShareResource shareresource=new ShareResource(10);
SaleThread salethread1=new SaleThread("售票1",shareresource);
SaleThread salethread2=new SaleThread("售票2",shareresource);
salethread1.start();
salethread2.start();}
}