我是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();
}
}
以下是错误发生位置的屏幕截图
任何帮助对我来说都很棒并且感激不尽。
提前感谢所有人:)
答案 0 :(得分:0)
你得到一个编译错误,而不是一个知道包含哪一行有用的异常。
您正在使用tr
,但未将其传递给TrainReservationCancel类。
尝试更改构造函数以获取TrainReservation
TrainReservationCancel(int noOfSeats, TrainReservation tr)
{
this.noOfSeats=noOfSeats;
this.trainAvailability=tr.trainAvailability;
}
并在主
TrainReservation tr=new TrainReservation(2);
TrainReservationCancel tr1=new TrainReservationCancel(1, tr);
顺便说一句:你想让你的课程implements Runnable
而不是extends Thread
答案 1 :(得分:0)
trainAvailability = tr.trainAvailability; tr未在此类中声明
如果你在线程环境中执行此操作并阅读变量,那么最好将它们声明为易失性