how to break a thread in another class

A

aleel

I am a beginner .Thank for your help !
I constructed three classes ManyThreadsTest,Timer and
Calculator.class Timer and Calculator implements the Runable interface
,class ManyThreadsTest
includes two static variables t1 and t2,then in the static field of
ManyThreadsTest announces :
static {
t1=new Thread (new Timer());
t2 =new Thread (new Calculator());
}
then in the main function as follows :
public static void main(String[] args) {

t1 = new Thread(new Timer());
t2 = new Thread(new Calculator());
t1.start();
t2.start();
while(true)
try {
Thread.sleep(100);
}
catch (InterruptedException ex) {
}
}
}
and the run function of the Calculator as follows :
public void run() {

for (int i = 0; i <= 5000; i++) {
String str = "a prime number!";
if (isPrimeNum(i)) {
System.out.println(i + " is " + str);
}
else {
System.out.println(i + " is not " + str);
}
}
ManyThreadsTest.t1.destroy();
char c;
try {
c = (char) System.in.read();
if(c=='q')
System.exit(0);
} catch (IOException e) {

e.printStackTrace();
}


}
the class Timer is used to record time , and the class Calculator
is used to judge a number which is lower than 10000 is a prime number
or not ,I want to break the Thread t1(used to record time )after the
Calculator finished its work .so I writed
"ManyThreadsTest.t1.destroy();" in the run function of Calculator
class .however, I found the Thread t1 continued after the destroy ()be
executed ,and the screen showed the time at all times.I wanted
originally to input the char "q" to make the program leave .but I
cannot do so now .how to solve the problem ?
 
C

chris

aleel said:
the class Timer is used to record time , and the class Calculator
is used to judge a number which is lower than 10000 is a prime number
or not ,I want to break the Thread t1(used to record time )after the
Calculator finished its work .so I writed
"ManyThreadsTest.t1.destroy();" in the run function of Calculator
class .however, I found the Thread t1 continued after the destroy ()be
executed ,and the screen showed the time at all times.I wanted
originally to input the char "q" to make the program leave .but I
cannot do so now .how to solve the problem ?

You would do better to use the t1.interrupt(), having first ensured that t1
is in a nice long Thread.sleep(). The online documentation(*) for destroy()
says "this method is not implemented", and just as well too.

(*) For JDK 1.4.2 anyway. But I think this documented non-implememtation
goes back a long way.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,231
Members
46,820
Latest member
GilbertoA5

Latest Threads

Top