一般来说创建线程的方法有三种,分别是:
1.继承Thread类来创建一个线程
第一步:定义一个类继承Thread类,并实现run()方法,run()方法中的内容即为线程需要完成的功能
class MyThread extends Thread{
String name;
public MyThread(String name) {
this.name = name;
System.out.println("继承Thread类");
}
@Override
public void run() {
for(int i = 1; i < 50; i++) {
System.out.println(this.name + ":" + i);
}
}
}
第二步:构建子类对象,并调用对象的start()方法启动线程
public class createThread {
public static void main(String[] args) {
//创建子类的对象
MyThread thread1 = new MyThread("one");
MyThread thread2 = new MyThread("two");
//启动线程
thread1.start();
thread2.start();
}
}
2.实现Runnable接口来创建一个线程
第一步:定义一个类实现Runnable接口,并实现接口中的run()方法
class MyThread2 implements Runnable{
@Override
public void run() {
// System.out.println("this"+this);
// System.out.println("Thread" + Thread.currentThread());
for(int i = 0; i < 50; i++) {
System.out.println(Thread.currentThread().getName()+":"+i);
}
}
}
第二步:创建该类对象,再创建一个Thread类对象,并把实现Runnable接口的类的对象作为参数传给Thread类对象,并调用start()方法
public class createThread {
public static void main(String[] args) {
//创建Runnable类对象
MyThread2 t1 = new MyThread2();
MyThread2 t2 = new MyThread2();
//把对象作为实参传递给Thread类
Thread thread3 = new Thread(t1,"three");
Thread thread4 = new Thread(t2,"four");
thread3.start();
thread4.start();
}
注意:创建的Runnable实现类只是一个target,不是线程对象,它用来指明线程运行时需要做的任务,Thread类的对象才是线程对象。
实现Runnable接口来创建一个类的好处:
- 一个Runnable实现类可以传给多个线程对象,所以适合多个相同程序代码的线程去处理同一个资源的情况,把线程和代码、数据有效的分离。
- Thread类创建线程是采用继承的方式,而Java中只能单继承。如果某个类的子类需要创建线程,那么就只能采用实现Runnable接口或者实现Callable接口的方式。
3.实现Callable接口来创建一个线程
先定义一个Callable的实现类,