1.创建多线程的两种方式

1.在Thread子类覆盖的run方法中编写运行代码

Thread t1 = new Thread(){
	public void run() {
		while(true){
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("t1:"+Thread.currentThread().getName());
			//this代表run方法所在的对象,即t1
			//System.out.println("t1:"+this.getName());
		}
	}
};
t1.start();
不能在run方法声明上抛出InterruptedException异常,以便省略run方法内部对Thread.sleep()语句的try…catch处理
2.在传递给Thread对象的Runnable对象的run方法中编写代码

Thread t2 = new Thread(new Runnable(){
	public void run() {
		while(true){
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("t2:"+Thread.currentThread().getName());
		}
	}
});
t2.start();
问:为什么都是采用Runnable这种方式创建线程?

答:体现了面向对象性, 因为run()方法在Runnable对象里面和Thread对象解耦
3.看如下代码,会输出什么结果?

new Thread(new Runnable(){
	public void run() {
		while(true){
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("Runnable:"+Thread.currentThread().getName());
		}
	}
}){
	public void run() {
		while(true){
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("Thread:"+Thread.currentThread().getName());
		}
	}
}.start();
输出结果:

Thread:Thread-2
原因是:只会运行子类的run()方法,因为根据源码是先看子类有没有run()方法, 如果有,就覆盖父类的run()方法。所以执行子类的run()方法,如果子类没有run()方法,就运行构造器里的Runnable()的run()方法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值