【发布时间】:2018-03-04 01:17:24
【问题描述】:
这是代码...
import java.util.Scanner;
class Draft extends Thread
{
String name;
static int counter;
boolean islive; //...
// the constructor
public Draft(String name, int counter, boolean islive)
{
this.name = name;
this.counter = counter;
this.islive = islive; //...
}
void stopTheThread()
{
this.islive = false; //...
}
@Override
public void run()
{
while(islive) //...
{
counter++;
try
{
sleep(913);
}
catch (InterruptedException e) { }
}
}
// the main function
public static void main(String[] args)
{
// intializing two threads
Draft Tone = new Draft("Tone", 13, true);
Draft Ttwo = new Draft("Ttwo", 26, true);
System.out.println("All Thread Started!");
Tone.start(); Ttwo.start();
Scanner scan = new Scanner(System.in);
String go = "";
// the while loop.......
while(!go.toLowerCase().equals("exit")) {
System.out.println(); //just a new line
System.out.print("Command: ");
go = scan.next();
if(go.equals("1")) {
System.out.print("Thread one "+ Tone.counter);
}
else if(go.equals("2")) {
System.out.print("Thread wo: "+ Ttwo.counter);
}
else if(go.equals("1Stop")) {
Tone.stopTheThread(); //is not stoping
System.out.print("Thread one Stopped"); //but printing
}
else if(go.equals("2Stop")) {
Ttwo.stopTheThread(); //is not stopping too
System.out.print("Thread two Stopped"); //printing too
}
}//end of the while
}//end of main
} //end of Draft
我为我的 Draft 类扩展了 Thread 类。 在 run 方法中,线程主要在 isive 条件下的 while 循环上运行,该条件是一个布尔值。
我创建了一个方法 stopTheThread 将 isalive 设置为 false 并且 run 方法上的循环应该停止. 但实际上,当我在 Tone 和 Ttwo 的主要方法中调用它时,它并没有停止。两者都是在 main 方法上创建的两个线程对象。
检查所有条件。
我做错了什么?
【问题讨论】:
标签: java multithreading methods constructor boolean