继承Thread
调用线程对象的start方法启动线程,不能直接调用run方法,否则是单线程Java采用的是单根继承体系,所以一旦继承于Thread类,则不能继承其它类,启动线程的唯一方法就是通过Thread类的start()实例方法,不能直接调用run()方法。从语法上来说没有错误,但是不是多线程。start()方法是一个native方法,它将启动一个新线程,并执行run()方法。这种方式实现多线程很简单,通过自己的类直接extend Thread,并复写run()方法,就可以启动新线程并执行自己定义的run()方法。
new Thread的弊端
1、每次new Thread新建对象性能差。
2、线程缺乏统一管理,可能无限制新建线程,相互之间竞争及可能占用过多系统资源导致死机或oom。
3、缺乏更多功能,如定时执行、定期执行、线程中断。
public class Test1 {
public static void main(String[] args) {
System.out.println(Thread.currentThread()); //获取当前线程对象
//方法1.2
Thread t2=new Thread() {
@Override
public void run() {
for(int i=0;i<50;i++) {
System.out.println("右手"+Thread.currentThread());
try {
Thread.sleep(150);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
// t2.run();
Thread t1=new MyThread3();
t1.start();
t2.start();
}
}
//方法1.1
class MyThread3 extends Thread{
@Override
public void run() {
for(int i=0;i<50;i++) {
System.out.println("左手"+Thread.currentThread());
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
实现Runnable接口
源代码
@FunctionalInterface 注解声明是函数式接口
public interface Runnable {
public abstract void run();
}
问题:定义run()方法没有返回值
public class Test2 {
public static void main(String[] args) {
Thread t1 = new Thread(new MyRunnable());
t1.start();
// 方法2.2
new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("中间手...."+Thread.currentThread());
try {