Java多线程两种实现方式

方法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点:

  1. mt1.join( )是等待线程死亡,对该方法必须捕捉异常, 或通过throws关键字指明可能要发生的异常。
  2. 对一个线程不能调用start( )两次,否则会产生 IllegalThreadStateException异常
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值