在 Java 中向线程 class 添加函数
Adding functions to Thread class in Java
我写了一个简单的时钟 class 来模拟时间 我需要它与其他线程同时 运行 所以我让它线程化 我有一些额外的方法来获取单位在我的系统中使用的时间,但现在我已将其更改为线程系统,我似乎无法掌握它们。
这是时钟的代码class
public class Clock extends Thread {
private Integer seconds;
private Integer minute;
private Integer hour;
public Clock()
{
setClock(0,0,0);
}
public void setClock(int hr, int min, int sec)
{
if(0 <= hr && hr < 24)
{
hour = hr;
}
else
{
hour = 0;
}
if(0 <= min && min < 60)
{
minute = min;
}
else
{
minute = 0;
}
if(0 <= sec && sec < 60)
{
seconds = sec;
}
else
{
seconds = 0;
}
}
public void tick()
{
this.seconds += 5;
this.minute += (int)(this.seconds/60);
this.seconds = this.seconds % 60;
this.hour += (int)(this.minute/60);
this.minute = this.minute % 60;
this.hour = this.hour % 24;
}
public int getMin()
{
return this.minute;
}
public int getHour()
{
return this.hour;
}
public String getTime()
{
return minute.toString() + "m" + seconds.toString() + "s";
}
public void run()
{
tick();
}
}
运行 上面的三个函数是导致问题的原因线程。
这是线程声明
Thread clock1 = new Clock();
我以正常的方式启动它,即开始然后加入,因为我正在 运行宁多个线程。
Thread TestJunc4 = new CarPark(100,TestTemp4,clock1);
我将该线程传递给其他需要它的线程,然后尝试进行这样的调用,我只给出语句的顶部,因为其余部分似乎并不重要。
while(clock.getHour() != 1)
问题是我无法调用 getHour 之类的 get 方法我正在使用 net beans,当我获得函数列表时它们不会显示在其中,如果我手动添加它们我会得到找不到它们的错误。
您的时钟 class 正在扩展线程。所以 Clock 的实例也是一个线程。
这意味着无处不在,java api 需要一个可以传递时钟对象的线程。但是当你需要你的实现的特殊方法时。你必须把它作为时钟传递。
Clock clock1 = new Clock();
我写了一个简单的时钟 class 来模拟时间 我需要它与其他线程同时 运行 所以我让它线程化 我有一些额外的方法来获取单位在我的系统中使用的时间,但现在我已将其更改为线程系统,我似乎无法掌握它们。
这是时钟的代码class
public class Clock extends Thread {
private Integer seconds;
private Integer minute;
private Integer hour;
public Clock()
{
setClock(0,0,0);
}
public void setClock(int hr, int min, int sec)
{
if(0 <= hr && hr < 24)
{
hour = hr;
}
else
{
hour = 0;
}
if(0 <= min && min < 60)
{
minute = min;
}
else
{
minute = 0;
}
if(0 <= sec && sec < 60)
{
seconds = sec;
}
else
{
seconds = 0;
}
}
public void tick()
{
this.seconds += 5;
this.minute += (int)(this.seconds/60);
this.seconds = this.seconds % 60;
this.hour += (int)(this.minute/60);
this.minute = this.minute % 60;
this.hour = this.hour % 24;
}
public int getMin()
{
return this.minute;
}
public int getHour()
{
return this.hour;
}
public String getTime()
{
return minute.toString() + "m" + seconds.toString() + "s";
}
public void run()
{
tick();
}
}
运行 上面的三个函数是导致问题的原因线程。
这是线程声明
Thread clock1 = new Clock();
我以正常的方式启动它,即开始然后加入,因为我正在 运行宁多个线程。
Thread TestJunc4 = new CarPark(100,TestTemp4,clock1);
我将该线程传递给其他需要它的线程,然后尝试进行这样的调用,我只给出语句的顶部,因为其余部分似乎并不重要。
while(clock.getHour() != 1)
问题是我无法调用 getHour 之类的 get 方法我正在使用 net beans,当我获得函数列表时它们不会显示在其中,如果我手动添加它们我会得到找不到它们的错误。
您的时钟 class 正在扩展线程。所以 Clock 的实例也是一个线程。 这意味着无处不在,java api 需要一个可以传递时钟对象的线程。但是当你需要你的实现的特殊方法时。你必须把它作为时钟传递。
Clock clock1 = new Clock();