我是java编码的新手......我正在尝试实现一个说明多任务处理的程序。在编程时我被一个小任务打动了,我无法找到它的方法。进入详细信息,我有 3 个类,如果我单独声明变量,我可以成功完成我的任务,但我想要这样一种要求,我想在另一个类中使用一个类的变量。即使我声明了变量作为公众,它抛出异常/错误。这是我的实现代码,以便专家清楚地理解!
class TrainReservation extends Thread
{
public int trainAvailability=1, bearthAvailability=1;
int noOfSeats;
TrainReservation(int noOfSeats)
{
this.noOfSeats=noOfSeats;
}
public void run()
{
if((trainAvailability >= noOfSeats) && (bearthAvailability >= noOfSeats))
{
System.out.println("seat is reserved");
trainAvailability=trainAvailability-noOfSeats;
bearthAvailability=bearthAvailability-noOfSeats;
System.out.println(trainAvailability);
}
else
System.out.println("no seats available");
}
}
class TrainReservationCancel extends Thread
{
int trainAvailability;
trainAvailability=tr.trainAvailability;
int noOfSeats;
TrainReservationCancel(int noOfSeats)
{
this.noOfSeats=noOfSeats;
}
public void run()
{
if(noOfSeats!=0)
{
bearthAvailability=bearthAvailability+noOfSeats;
trainAvailability=trainAvailability+noOfSeats;
System.out.println(bearthAvailability);
}
}
}
class MainClass
{
public static void main(String[] args)
{
TrainReservation tr=new TrainReservation(2);
TrainReservationCancel tr1=new TrainReservationCancel(1);
Thread obj=new Thread(tr);
tr.start();
Thread obj1= new Thread(tr1);
tr1.start();
}
}
这是错误所在的屏幕截图
任何帮助对我来说都会很棒,并表示赞赏。
提前谢谢大家:)