Java多线程之传统线程回顾

一:创建线程的两种方式:  1.在Thread子类覆盖的run方法中编写运行代码  2.在传递个Thread类得run方法中编写代码

           问题: 此时涉及一个以往的知识点:能否在run方法声明上抛出 InteruptedException异常,以便省略run方法内部对Thread.sleep()语句的 try...catch处理

           答案:不能抛出:原因是子类继承父类,按照进化论,那么子类比父类更先进,那么能处理更多的异常,而Thread本身没有异常,所以不能抛出。

          总结:1.java是面向对象语言,有很多时候,生活中的细节可以帮助程序中晦涩的部分的理解                        2.查看thread类得run方法的源代码,可以看到其实这两种方式都是在调用Thrad对象的run方法,如果Thread类的run方法没有被覆盖,并且为该Thread对象设置了一个Runnable对象,该run方法会调用Runnable对象的run方法

 
package com.czq.thread;

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(Thread.currentThread().getName()+": 1"); 
					//这里的this表示的是当前方法(run)所在的对象
					System.out.println(this.getName()+"this");
				}
			}
			
		};
		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(Thread.currentThread().getName()+": 1"); 
				}
			}
			
		});
		thread2.start();
		
		
		//new Thread(new Runable.run){run}.start()这样的话执行start方法会去找类里面 的run方法,
		//然后又类里面得run方法没有的话会去找父类里面的run方法,父类会访问runable
		//也就是说如果子类的方法覆盖了父类的方法,那么子类的方法,如果没有覆盖,那 么找父类的方法
		new Thread(
			new Runnable(){
				public void run(){
					while(true){
						try {
							Thread.sleep(500);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
						System.out.println("runable"+Thread.currentThread().getName()+": 1"); 
					}
				}
			}		
		
		){
			
			public void run(){
				while(true){
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println("thread"+Thread.currentThread().getName()+": 1"); 
				}
			}
		}.start();

	}

}

后半部分的执行结果是后面这句的run方法


 总结一:new Thread(new Runable.run){run}.start()

首先start()找自己来里面的run方法,如果自己的类里面找不到run方法,那么再找父类的run方法,而这里的父类执行的是runable的方法
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值