多线程两种实现方式的区别

Java里有两种多线程的实现方式,一种是继承Thread类,一种是实现Runnable接口,面试时候突然被问到这两种方式有什么区别呢?

我一直习惯性的使用实现Runnable接口的方式来实现多线程,但是它们有什么区别?还真没细想过。。。。于是问了问度受,答案真是("▔□▔) 。。。好吧用的时候知道但是说却一时说不出。。哎语文老师死得太早了

第一种方式,继承Thread类:

public class Test {
	public static void main(String args[]) throws IOException, Exception {
		ThreadTest t1 = new ThreadTest();
		ThreadTest t2 = new ThreadTest();
		ThreadTest t3 = new ThreadTest();
		t1.start();
		t2.start();
		t3.start();
	}
}

class ThreadTest extends Thread {
	private int total = 10;
	
	@Override	
	public void run() {
		// TODO Auto-generated method stub
		while(total>0){
			total--;
			System.out.println("now total value is:" + total);
			
		}
		
	}
}
运行结果:

now total value is:9
now total value is:8
now total value is:7
now total value is:6
now total value is:5
now total value is:4
now total value is:3
now total value is:2
now total value is:1
now total value is:0
now total value is:9
now total value is:8
now total value is:7
now total value is:6
now total value is:9
now total value is:8
now total value is:7
now total value is:6
now total value is:5
now total value is:4
now total value is:3
now total value is:2
now total value is:1
now total value is:0
now total value is:5
now total value is:4
now total value is:3
now total value is:2
now total value is:1
now total value is:0

第二种方式,实现runnable接口:

public class Test {
	public static void main(String args[]) throws IOException, Exception {
		Runnable r = new RunnableTest();
		Thread t1 = new Thread(r);
		Thread t2 = new Thread(r);
		Thread t3 = new Thread(r);
		t1.start();
		t2.start();
		t3.start();
	}
}

class RunnableTest implements Runnable {
	private int total = 10;
	
	@Override	
	public void run() {
		// TODO Auto-generated method stub
		while(total>0){
			total--;
			System.out.println("now total value is:" + total);
			
		}
		
	}
}

运行结果:

now total value is:8
now total value is:8
now total value is:7
now total value is:5
now total value is:6
now total value is:3
now total value is:4
now total value is:1
now total value is:2
now total value is:0

简单来说就是第一种方法是多线程执行多个任务,第二种方法是多线程执行单个任务。第二个方法由于(本人太懒测试程序)没使用同步关键字明显的出现了读写脏数据的现象。事实上我一般想要多线程执行多个任务时也是习惯于用第二种方法只是多实例化几个Runnable实例,于是这问题我死活也答不出来啊= =

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值