1、继承Thread类,实现多线程。
java里提供了java.lang.Thread类,继承Thread类实现run方法。
范例:
public class MyThread extends Thread{
private String name;
public MyThread(String name) {
this.name = name;
}
public void run() {
for(int i = 0; i < 5; i++) {
System.out.println(name + " == " + i);
}
}
public static void main(String[] args) {
new MyThread("线程1").start();
new MyThread("线程2").start();
new MyThread("线程3").start();
}
}
2、基于Runnable接口,实现多线程
虽然通过继承java.lang.Thread类可以实现多线程,但是java中继承存在单继承问题,所以出现了第二种实现多线程方式:实现Runnable接口
范例:
public class MyRunnable implements Runnable{
private String name;
public MyRunnable(String name) {
this.name = name;
}
public void run() {
for(int i = 0; i < 5; i++) {
System.out.println(name + " == " + i);
}
}
public static void main(String[] args) {
Thread thread1 = new Thread(new MyRunnable("线程1"));
Thread thread2 = new Thread(new MyRunnable("线程2"));
Thread thread3 = new Thread(new MyRunnable("线程3"));
thread1.start();
thread2.start();
thread3.start();
}
}
线程运行状态
使用Thread类调用start()方法,并不意味着线程已经开始运行。
(1)、使用Thread类调用start()方法之后,线程会进入就绪状态。
(2)、进入就绪状态之后,会进行资源调度,当调度成功之后会进入run()方法。所有线程不可能一直执行,当线程需要释放资源时,会进入线程阻塞状态,释放资源让其它线程调度,之后如果这个线程重新回归,会进入就绪状态,依次循环。
(3)、当run()方法执行完毕,线程完成任务,会进入停止状态。
要点:
- 每个线程类的对象只允许启动一次,重复启动会报错。
- 所有线程对象都是交替执行,执行顺序不可控制。
- 任何情况下,只要定义了多线程,启动多线程的方法只有一种方案:Thread 类中 start() 方法。
- Thread 是 Runnable子类。
- Runable解决了Thread单继承的局限性。