四、实现java.lang.Runnable接口
/**
* 通过实现 Runnable 接口实现多线程
*/
public class TestMitiThread1 implements Runnable {
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName() + " 线程运行开始!");
TestMitiThread1 test = new TestMitiThread1();
Thread thread1 = new Thread(test);
Thread thread2 = new Thread(test);
thread1.start();
thread2.start();
System.out.println(Thread.currentThread().getName() + " 线程运行结束!");
}
public void run() {
System.out.println(Thread.currentThread().getName() + " 线程运行开始!");
for (int i = 0; i < 10; i++) {
System.out.println(i + " " + Thread.currentThread().getName());
try {
Thread.sleep((int) Math.random() * 10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + " 线程运行结束!");
}
}
运行结果:
main 线程运行开始!
Thread-0 线程运行开始!
main 线程运行结束!
0 Thread-0
Thread-1 线程运行开始!
0 Thread-1
1 Thread-1
1 Thread-0
2 Thread-0
2 Thread-1
3 Thread-0
3 Thread-1
4 Thread-0
4 Thread-1
5 Thread-0
6 Thread-0
5 Thread-1
7 Thread-0
8 Thread-0
6 Thread-1
9 Thread-0
7 Thread-1
Thread-0 线程运行结束!
8 Thread-1
9 Thread-1
Thread-1 线程运行结束!
说明:
TestMitiThread1类通过实现Runnable接口,使得该类有了多线程类的特征。run()方法是多线程程序的一个约定。所有的多线程代码都在run方法里面。Thread类实际上也是实现了Runnable接口的类。
在启动的多线程的时候,需要先通过Thread类的构造方法Thread(Runnable target) 构造出对象,然后调用Thread对象的start()方法来运行多线程代码。
实际上所有的多线程代码都是通过运行Thread的start()方法来运行的。因此,不管是扩展Thread类还是实现Runnable接口来实现多线程,最终还是通过Thread的对象的API来控制线程的,熟悉Thread类的API是进行多线程编程的基础。
|
|