Java多线程的实现方式
方式一 继承Thread类
public class Machine extends Thread {
private int a;
@Override
public void run() {
for (a = 0; a < 50; a++) {
System.out.println(currentThread().getName() + ":" + a);
try {
sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
int a = 0;
Machine machine1 = new Machine();
Machine machine2 = new Machine();
machine1.start();// 开启线程
machine2.start();
machine1.run(); // 主线程调用machine1的run 方法,不建议这样调用 仅仅用于测试
}
}
Thread类的两个重要方法:
run():包含线程运行时所执行的代码
start():用于启动线程
方式二 实现Runnable
public class MachineRunnable implements Runnable {
private int a = 0;
public void run() {
for (a = 0; a < 50; a++) {
System.out.println(Thread.currentThread().getName() + ":" + a);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
MachineRunnable machine = new MachineRunnable();
Thread thread1 = new Thread(machine);
Thread thread2 = new Thread(machine);
thread1.start();
thread2.start();
}
}
Thread(Runnable runnable) // 当线程启动时,会执行runnable所引用对象的run() 方法
总结
- Thread类本身也实现了Runnable接口,因此也可以作为以上构造方法的参数
- 方式一中的 currentThread().getName() 相当于
Thread thread = Thread.currentThread();// 返回当前正在执行代码的引用
String name = thread.getName();// 获得当前线程的名字
- 当执行 machine.start()时,start()方法并没有启动一个新的Machine 线程,而是去调用Machine对象的run()方法,这只是普通的方法调用。所有的方法调用都由主线程完成
- 一个线程只能被启动一次,如下代码第二次调用。start()方法时会抛出IlleaglThreadStateException异常
Machine machine = new Machine();
machine.start();machine.start(); // 抛出java.lang.IlleaglThreadStateException异常
注:本书学习内容和代码,来源自《JAVA 面向对象编程》(第二版)作者:孙卫琴