在 java中,怎样创建一个线程

2024-11-16 09:53:07
推荐回答(2个)
回答1:

package test;
import java.util.*;

public class Threadtest extends Thread{
int pauseTime;
String name;
public Threadtest(int time,String n){
pauseTime = time;
name = n;
}
public void run(){
Calendar now;
now = Calendar.getInstance();
System.out.println(name+now.get(Calendar.MINUTE)+now.get(Calendar.SECOND));
try{
Thread.sleep(pauseTime);
}catch(Exception e){
e.getStackTrace();
}
Threadtest2 myt1 = new Threadtest2(5000,"threadin;;");
myt1.start();
}
public static void main(String[] args){
Threadtest myt1 = new Threadtest(2000,"thread1;;");
myt1.start();
Threadtest myt2 = new Threadtest(1000,"thread2;;");
myt2.start();
}

}
class Threadtest2 extends Thread{
int pauseTime;
String name;
public Threadtest2(int time,String n){
pauseTime = time;
name = n;
}
public void run(){
Calendar now;
now = Calendar.getInstance();
System.out.println(name+now.get(Calendar.MINUTE)+now.get(Calendar.SECOND));
try{
Thread.sleep(pauseTime);
}catch(Exception e){
e.getStackTrace();
}
}

}

回答2:

创建线程有两种方式,推荐使用实现Runable接口方式