方法1:通过创建Thread类的子类实现多线程,步骤如下 :
1. 定义Thread类的一个子类。
2. 定义子类中的方法run( ),覆盖父类中的方法run( )。
3. 创建该子类的一个线程对象。
4. 通过start( )方法启动线程
public class Hello_Java {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Hello Java and Hello World");
UserThread t1,t2,t3,t4;
t1=new UserThread("1");
t2=new UserThread("2");
t3=new UserThread("3");
t4=new UserThread("4");
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class UserThread extends Thread{
int sleeptime;
public UserThread(String id) {
super(id);
sleeptime=(int)(Math.random()*1000);
System.out.println("线程号: "+getName()+",睡眠"
+sleeptime+"毫秒");
}
public void run(){
try{
Thread.sleep(sleeptime);
}catch(InterruptedException e) {
System.err.println("error"+e.toString());
}
System.out.println("运行的线程是:"+getName());
}
}
方法2:通过接口创建多线程,步骤如下
1.定义一个实现Runnable接口的类。
2.定义方法run( )。Runnable接口中有一个空的方法run( ), 实现它的类必须覆 盖此方法。
3.创建该类的一个线程对象,并将该对象作参数,传递给 Thread类的构造函数,从而生成Thread类的一个对象。
4.通过start( )方法启动线程
class UserMultThread implements Runnable{
int num;
UserMultThread(int n) {
num=n;
}
public void run( ) {
for(int i=0;i<3;i++) {
System.out.println("运行线程:"+num);
}
System.out.println("结束 : "+num);
}
}
public class multThreadZero{
public static void main(String args[ ])
throws InterruptedException {
Thread mt1=new Thread( new UserMultThread(1));
Thread mt2=new Thread( new UserMultThread(2));
mt1.start( );
mt2.start( );
mt1.join( ); // 等待线程死亡
mt2.join( );
}
}
• 需要注意的2点:
- mt1.join( )是等待线程死亡,对该方法必须捕捉异常, 或通过throws关键字指明可能要发生的异常。
- 对一个线程不能调用start( )两次,否则会产生 IllegalThreadStateException异常