传统线程技术(一)

一. 传统线程创建方法

1. 覆盖Thread子类的run方法中编写详细代码

2. 在传递给Thread的Runnable对象的run方法中编写详细代码


二. 实现代码

public class TraditionalThread {
	public static void main(String[] args) {
		// 方法1:直接new一个Thread的子类。让子类run方法覆盖父类的run方法
		Thread thread1 = new Thread() {
			@Override
			public void run() {
				while (true) {
					try {
						Thread.sleep(500);
						System.out.println(Thread.currentThread().getName());
					} catch (InterruptedException e) {
						e.printStackTrace();
					}

				}
			}
		};
		thread1.start();  

		// 方法2:给Thread类传一个实现了Runnable接口的类
		Thread thread2 = new Thread(new Runnable() {
			@Override
			public void run() {
				while (true) {
					try {
						Thread.sleep(500);
						System.out.println(Thread.currentThread().getName());
					} catch (InterruptedException e) {
						e.printStackTrace();
					}

				}
			}
		});
		thread2.start();
	}
}
小知识:

1. new Thread(){ 

    }   这样的写法事实上是创建了Thread的子类

2. new Thread(new Runnable(){}){

    }   传递给Thread的參数事实上是Runnable的实现类对象


三. 一个典型样例:

请问以下的类是运行Runnable中的run方法还是Thread子类的方法?

public class Test {
	public static void main(String[] args) {
		// 以下的代码将会执行Thread子类的run方法而不会执行runnable中的run方法
		new Thread(new Runnable() {
			@Override
			public void run() {
				while (true) {
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println("Runnable:" + Thread.currentThread().getName());
				}
			}
		}) {
			@Override
			public void run() {
				while (true) {
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println("Thread:" + Thread.currentThread().getName());
				}
			}
		}.start();
	}
	
	/**
	 * Thread 类中的run方法
	 * private Runnable target;
	 * 
	 * public void run() {
	 *	  if (target != null) {
	 *		  target.run();
	 *	  }
	 * }
	 **/
}
答案是执行Thread子类的run方法。 由于它覆盖了父类的run方法,根本就不会执行到runnable的方法,即target.run()



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值