Java中的两种开线程方式

1.  使用 extends继承Thread类,然后在 主函数中 调用创建的这个类,创建其类对象,然后再利用对象访问start 方法。

package testThread;

public class thr {
	public static void main(String args[]) throws InterruptedException{
		for(int j =0;j<200;j++){
			System.out.println(Thread.currentThread().getName()+" "+j);
			if(j==50){
				Thread.sleep(3000);
				Thread th1 = new MyThread();
				Thread th2 = new MyThread();
				th1.start();
				th2.start();
			}
		}
	}
}

class MyThread extends Thread{
	public void run()
	{
		for(int i = 0;i<100;i++){
			System.out.println(Thread.currentThread().getName()+" "+i);
		}
	}
}

2. 实现Runnable这个接口,再在主类里面调用这个接口,调用的方式是通过传参的方式,看代码就明白了。

package testThread;

public class thr1 {
	public static void main(String args[]){
		for(int j = 0;j<150;j++){
			System.out.println(Thread.currentThread().getName()+" "+j);
			if(j==60){
				try{
					Thread.sleep(5000);
				}catch(Exception e){
					e.printStackTrace();
				}
				Thread th1 = new Thread(new runn());
				Thread th2 = new Thread(new runn());
				th1.start();
				th2.start();
			}
		}
	}
}

class runn implements Runnable{
	public void run(){
		for(int i = 0;i<100;i++){
			System.out.println(Thread.currentThread().getName()+" "+i);
		}
	}
}

希望能够帮到你~~~

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值