1.在java中,创建线程一般只有两种方法;1)继承Thread;2)实现Runnable接口;
2.继承Thread类:
class MyThread extends Thread{
private String name;
public MyThread(String name){
this.name = name;
}
//继承Thread类的话,必须重写run方法,在run方法中定义需要执行的任务
@Override
public void run() {
System.out.println("name:"+name+" 子线程ID:"+Thread.currentThread().getId());
}
}
public class test {
public static void main(String[] args) {
MyThread thread1 = new MyThread("thread1");
thread1.start();
}
}
3.注意点 run和 start使用误区:
(1)线程启动要用start()方法,只有它才能创建一个新的线程来执行定义的任务。
(2)run方法只是定义了需要执行的任务,如果调用run方法,即相当于在主线程中执行run方法,跟普通的方法调用没有任何区别。
4.结果对比:
public class test {
public static void main(String[] args) {
System.out.println("主线程ID:"+Thread.currentThread().getId());
MyThread thread = new MyThread("thread");
thread.start();
thread.run();
MyThread thread2 = new MyThread("thread2");
thread2.run();
}
}
结论:1)调用了run()方法的子线程id与主线程id一致;不会创建新的线程,与普通方法调用一致。
2)调用了start()方法创建了新的线程。
5.实现Runnable接口:
public class Test {
public static void main(String[] args) {
System.out.println("主线程ID:"+Thread.currentThread().getId());
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
}
}
class MyRunnable implements Runnable{
public MyRunnable() {
}
@Override
public void run() {
System.out.println("子线程ID:"+Thread.currentThread().getId());
}
}
发现:1)这种方式必须将Runnable作为Thread类的参数,然后通过Thread的start方法来创建一个新线程来执行该子任务。
2)源代码中,Thread类是实现了Runnable接口方法的。
6.Thread与Runnable区别: