Java多线程之创建线程的两种传统方式

package javaplay.thread.test;

public class TraditionalThread {
	public static void main(String[] args) {
		// 第一种
		Thread thread = new Thread() {
			@Override
			public void run() {
				while (true) {
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println("1:" + Thread.currentThread().getName());
					System.out.println("2:" + this.getName());// 不建议这么做,第二种方式就不能用这种

				}
			}
		};
		thread.start();

		// 第二种 更加体现面向对象的思维 把运行代码封装到一个对象中
		Thread thread2 = new Thread(new Runnable() {

			@Override
			public void run() {
				while (true) {
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println("1:" + Thread.currentThread().getName());

				}

			}

		});
		thread2.start();

		// new Thread(runnable.run){run}.start();
		// 运行start方法就会去找当前对象身上的run方法,如果没找到自己的run方法就用自己父类的run方法
		// 父类的run方法会去找runnable,此例的匿名子类覆盖了父类的run方法没有去找runnable,之所以会找runnable
		// 是因为父类的run方法会去找runnable,只要不覆盖父类的run方法,就会去找runnable,如果覆盖了,就以覆盖的代码为准
		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());

				}

			}

		}) {
			public void run() {
				while (true) {
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println("thread:" + Thread.currentThread().getName());

				}
			}
		}.start();

		// 创建线程的两种传统方式,总结:查看Thread类的run方法的源代码,
		// 可以看到其实这两种方式都是在调用Thread对象的run方法,如果Thread类的run方法
		// 没有被覆盖,并且为该Thread对象设置了一个Runnable对象,该run方法会调用Runnable对象的run方法
		// 多线程下载:去抢了服务器的带宽,服务器可以同时为100个线程提供服务,为每个线程提供20k,一个线程只能是20k
	}
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值