1.继承Thread类
需要重写run方法,run方法的方法体就是线程要进行的任务,通过线程对象的start方法来启动线程
示例:
public class Main {
public static void main(String[] args) {
Thread mythread = new MyThread();
mythread.start();
}
}
class MyThread extends Thread{
@Override
public void run() {
for (int i=0;i<5;i++){
System.out.println(Thread.currentThread().getName()+i);
}
}
}
}
输出结果如下:
2.通过实现Runnable接口创建线程类
定义一个类实现Runnable接口,创建该类实例,将其作为构造参数传入Thread类实例对象
实例:
public class Main {
public static void main(String[] args) {
MyRunable myRunable = new MyRunable();
Thread thread = new Thread(myRunable);
thread.start();
}
}
class MyRunable implements Runnable{
@Override
public void run() {
for (int i=0;i<5;i++){
System.out.println(Thread.currentThread().getName()+i);
}
}
}
}
输出结果如下: