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

2024年11月16日 09:53
有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接口方式