本帖最后由 孙百鑫 于 2013-6-30 08:55 编辑
//通过继承Thread类实现多线程
public class Show{
public static void main(String[] args){
Thread t1 = new PrintChar('a', 100);
Thread t2 = new PrintChar('b', 100);
Thread t3 = new PrintNum(100);//此语句出错
t1.start();
t2.start();
t3.start();
}
}
class PrintChar extends Thread{
//数据域
private char printToChar;// char型变量 需打印的字母
private int time;// int型变量 需打印的次数
public PrintChar(char c, int t){//构造函数 用于初始化
printToChar = c;
time = t;
}
public void run(){//覆写run方法
for(int i = 0; i < time; i++){
System.out.print(printToChar);
}
}
}
class PrintNum extends Thread{
private int lastNum;
private PrintNum(int n){
lastNum = n;
}
public void run(){
for(int i = 1; i <= lastNum; i++){
System.out.print(" "+i);
}
}
}
//-----------------------------------------------------------------------------------------------------------------------------------------------------------
//后来又重写了一遍 貌似一样但是编译正常,Why
public class Show{
public static void main(String[] args){ Thread t1 = new PrintNum(100); Thread t2 = new PrintChar('A',100); t1.start(); t2.start(); }}
class PrintNum extends Thread{
private int num;
public PrintNum(int n){ num = n; }
public void run(){ for(int i = 1; i <= num; i++){ System.out.print(" "+i); } }}
class PrintChar extends Thread{
private char printToChar; private int printToTime;
public PrintChar(char c, int t){ printToChar = c; printToTime = t; }
public void run(){ for(int i = 1; i <= printToTime; i++){ System.out.print(" "+printToChar); } }}
|
|