您的位置:首页 > 其它

传统的创建线程的两种方式

2017-11-28 20:41 162 查看

1.传统的创建线程的两种方式

public class TraditionalThread {

// 第一种方式:继承Thread类
static class Thread1 extends Thread {

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

}

// 第二种方式:实现Runnable接口
static class Thread2 implements Runnable {

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

public static void main(String[] args) {
//
Thread1 t1 = new Thread1();
t1.setName("t1");

Thread t2 = new Thread(new Thread2(), "t2");

t1.start();
t2.start();
}

结果:
thread1(Thread.currentThread().getName()):t1
thread2(Thread.currentThread().getName()):t2


2. 比较两种实现方式的执行顺序

问题:

如果在Thread子类重写了run()方法,在创建这个类的对象时也传递一个Runnable对象并实现了run()方法,那么,线程运行时执行的代码是重写的run()方法还是Runnable中实现的run()方法?

public class TraditionalThread {

public static void main(String[] args) {

new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Runnable's run()...");
}
}){
@Override
public void run() {
System.out.println("Thread's run()...");
}
}.start(); // Thread's run()...

}
}

结果:
Thread's run()...


执行Runnable接口中的run()方法中的内容是父类Thread的run()方法的内容,当子类重写了run()方法,就不会再执行父类的run()方法,所有会执行重写的run()方法中的内容

3. 其他细节

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

不能:
Exception InterruptedException is not compatible with throws clause in Thread.run()
,不仅是InterruptedException,run()方法不支持抛出任何异常

(2) 多线程会提高程序的运行效率吗?

不会,反而会降低程序的运行效率

(3) 匿名内部类的构造方法如何调用父类的非默认构造方法?

class W {
private int i;
public W(int x) {i = x;}
public int value() {return i;}
}

public class Outer {

// 只需要简单的传递参数给基类的构造器即可
public W getW(int x) {
return new W(x) {
public int value() {
return super.value() * 47;
}
};
}

public static void main(String[] args) {
Outer out = new Outer();
W w = out.geW(10);
System.out.println(w.value());
}

}

结果:
470
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  线程