求助!关于线程的问题?各位大侠谢谢了!!!

03-10-31 彭飞2003
我想通过线程控制屏幕输入,但是我使用 InputStreamReader in = new InputStreamReader(System.in);

BufferedReader buf = new BufferedReader(in); 的buf.readLine()方法,所以在调用该方法的方法中加抛出例外,那么我在使用线程时,重写RUN()方法,但是也同样对RUN()方法加抛出例外,这样做对吗?代码如下:

public class Group extends Thread {

Vector v = new Vector();

public void run() throws IOException

{

InputStreamReader in = new InputStreamReader(System.in);

BufferedReader buf = new BufferedReader(in);

do {

person tmp = new person();

v.addElement(tmp);

String AgeTemp;

System.out.print("Input name:");

tmp.setName(buf.readLine());

System.out.print("Input age:");

AgeTemp = buf.readLine();

tmp.setAge(Integer.parseInt(AgeTemp)) ;

System.out.print("Input sex:");

tmp.setSex(buf.readLine()) ;

System.out.print("Input univ:");

tmp.setUniv(buf.readLine()) ;

System.out.println("type 'q' to finish input.");

} while (!buf.readLine().equals("q"));

}

public static void main(String args[]) throws IOException{

Vector v=new Vector();

Group gp = new Group();

gp.start();

//gp.SortMothd();

//gp.StrPrint();

//gp.SortMothd(man);

}

}

shilongwufeng
2003-11-03 09:13
在覆盖run()方法时,不能够抛出异常,否则会报错,改正如下:

import java.io.*;

import java.util.*;

public class MyThread extends Thread {

Vector v = new Vector();

public void run()

{

InputStreamReader in = new InputStreamReader(System.in);

BufferedReader buf = new BufferedReader(in);

try {

do {

Person tmp = new Person();

v.addElement(tmp);

String AgeTemp;

System.out.print("Input name:");

tmp.setName(buf.readLine());

System.out.print("Input age:");

AgeTemp = buf.readLine();

tmp.setAge(Integer.parseInt(AgeTemp));

System.out.print("Input sex:");

tmp.setSex(buf.readLine());

System.out.print("Input univ:");

tmp.setUniv(buf.readLine());

System.out.println("type 'q' to finish input.");

}

while (!buf.readLine().equals("q"));

}

catch (IOException ex) {

ex.printStackTrace();

}

}

public static void main(String args[]) throws IOException{

Vector v=new Vector();

MyThread gp = new MyThread();

gp.start();

//gp.SortMothd();

//gp.StrPrint();

//gp.SortMothd(man);

}

}

猜你喜欢