java多线程技术篇--创建线程的方式

来源:互联网 发布:中国禁书知乎 编辑:程序博客网 时间:2024/05/29 11:24

一、创建线程的两种方式:

1、在Thread子类重写的run方法中编写运行代码

能否在run方法声明上抛出interruptException异常,以便省略run方法内部对Thread.sleep()语句的try...catch处理

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


二、代码实现

package com.sinwao.thread01;public class TraditionalThread {public static void main(String[] args) {Thread thread = new Thread(){@Overridepublic void run() {while (true) {try {Thread.sleep(1000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println("1:"+Thread.currentThread().getName());System.out.println("2:"+this.getName());}}};thread.start();Thread thread2 = new Thread(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubwhile (true) {try {Thread.sleep(1000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println("3:"+Thread.currentThread().getName());}}});thread2.start();new Thread(new Runnable() {@Overridepublic void run() {while (true) {try {Thread.sleep(1000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println("runnable:"+Thread.currentThread().getName());}}}){public void run() {while (true) {try {Thread.sleep(1000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println("thread:"+Thread.currentThread().getName());}}}.start();}}


三、总结

查看Thread类的run()方法的源码

Runnable target;

  public void run() {        if (target != null) {            target.run();        }    }

可以看到其实两张方式都是在调用Thread对象的run()方法,如果Thread类的run方法没有被重写,并且为该Thread对象设置了一个Runnable对象,该run方法会调用Runnable对象的run方法


代码实现中的第三种线程开启方式会出现什么问题?

如果在Thread子类覆盖的run方法中编写了代码,也为Thread子类对象传递了一个Runnable对象,那么线程运行时执行代码是子类的run方法的代码?还是Runnable

对象的run方法的代码?

这种情况下会调用Thread子类的run方法,而不是Runnable对象的run方法。

那么匿名内部类对象的构造方法如何调用父类的非默认构造方法?

定义一个接口Ainterface A{public int add(int b,int c);}在main方法中加上new A(){/*这里的new A() 就是调用构造方法 如有有参数的就直接写参数就行了 new A("aa") 着样就行匿名内部类不能重新定义新的构造方法*/public int add(int b, int c) {return b+c;}};

继续思考:

1、多线程机制会提高程序的运行效率吗?

不会提高程序运行效率,有可能还会降低效率。因为线程耗费的是cpu的执行时间片。

2、为什么会有多线程下载?

因为这个跟服务器的设定有关,服务器限制一个线程只能拥有50k的下载速率,10个线程就能获取500k的下载速率,于是就出现了多个线程同时请求获取服务器端资源,这样就提高了下载速度。