实现多线程的两种方法
1. 继承Thread类
- extends Thread
- 重写run方法
- 调用start方法启动线程
public class TestThread extends Thread{
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println("我在学习多线程"+i);
}
}
public static void main(String[] args) {
TestThread tt=new TestThread();
tt.start();
for (int i = 0; i < 100; i++) {
System.out.println("我在摸鱼"+i);
}
}
}
2. 实现Runnable接口
- implements Runnable
- 重写run方法
- 创建线程对象
- 调用start方法启动线程
public class TestRunnable implements Runnable {
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println("我在学习多线程"+i);
}
}
public static void main(String[] args) {
TestRunnable tr=new TestRunnable();
new Thread(tr).start();
for (int i = 0; i < 100; i++) {
System.out.println("我在摸鱼"+i);
}
}
}
推荐使用第二种,方便同一个对象被多个线程使用