1>实现Runable接口
1.创建Runable的实现类
2.在实现类中重写Runable接口的run方法
3.创建Thread对象,构造方法中传递Runable接口的实现对象
4.调用Thread中的start方法
public class myThread2 implements Runnable{
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println(Thread.currentThread().getName() + i);
}
}
}
public static void main(String[] args) {
myThread2 myThread2 = new myThread2();
Thread thread = new Thread(myThread2);
thread.start();
for (int i = 0; i < 20; i++) {
System.out.println(Thread.currentThread().getName() + i);
}
}
2>创建Thread的子类
1.创建一个Thread的子类
2.在子类里重写Thread的run方法,设置线程任务
3.创建Thread子类的对象
4.调用对象的方法start
void start()使该线程开始执行,java虚拟机调用该线程的run方法
public class myTherad extends Thread{
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println(Thread.currentThread().getName() + i);
}
}
}
public static void main(String[] args) {
myTherad myTherad = new myTherad();
myTherad.start();
for (int i = 0; i < 20; i++) {
System.out.println(Thread.currentThread().getName() + i);
}