Java实现多线程有两种方式:一是继承Thread类;二是实现Runable接口。
一、Thread实现
publicclass ThreadDemo2 {
publicstaticvoid main(String[] args) {
new TestThread2().start();
inti = 0;
while(i++ < 100) {
System.out.println("main thread is running");
}
}
}
class TestThread2 extends Thread {
publicvoid run() {
intj = 0;
while(j++ < 100) {
System.out.println(Thread.currentThread().getName() + " is running!");
}
}
}
运行结果:
二、Runnable实现
publicclass ThreadDemo3 {
publicstaticvoid main(String[] args) {
TestThread3 t3 = new TestThread3();
Thread t = new Thread(t3);
t.start();
inti = 0;
while(i++ < 100) {
System.out.println("main thread is running");
}
}
}
class TestThread3 implements Runnable {
publicvoid run() {
intj = 0;
while(j++ < 100) {
System.out.println(Thread.currentThread().getName() + " is running!");
}
}
}
运行结果: