Java多线程的几种实现方式
1、继承Thread类
public class MultiThread {
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName() + "线程开始运行...");
MultiSayThread t1 = new MultiSayThread("A");
MultiSayThread t2 = new MultiSayThread("B");
t1.start();
t2.start();
System.out.println(Thread.currentThread().getName() + "线程結束运行...");
}
}
class MultiSayThread extends Thread {
public MultiSayThread(String threadName) {
super(threadName);
}
public void run() {
System.out.println(getName() + "线程运行开始...");
for (int i = 0; i < 10; i++) {
try {
System.out.println(i + " " + getName());
sleep((int) Math.random() * 10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(getName() + "线程运行结束...");
}
}
程序运行结果:
main线程开始运行...
main线程結束运行...
A线程运行开始...
B线程运行开始...
0 A
0 B
1 B
1 A
2 B
2 A
3 B
3 A
4 B
4 A
5 B
5 A
6 B
6 A
7 B
7 A
8 B
8 A
9 B
9 A
B线程运行结束...
A线程运行结束...
2、实现Runnable
package com.huawei.testthread;
public class MultiRunnable {
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName() + "线程开始运行...");
MultiSaidThread r1 = new MultiSaidThread();
MultiSaidThread r2 = new MultiSaidThread();
Thread t1 = new Thread(r1, "A");
Thread t2 = new Thread(r2, "B");
t1.start();
t2.start();
System.out.println(Thread.currentThread().getName() + "线程结束运行...");
}
}
class MultiSaidThread implements Runnable {
public void run() {
System.out.println(Thread.currentThread().getName() + "线程开始运行...");
for (int i = 0; i < 10; i++) {
try {
System.out.println(i + " " + Thread.currentThread().getName());
Thread.sleep((int) Math.random() * 10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + "线程结束运行...");
}
}
程序运行结果:
main线程开始运行...
main线程结束运行...
A线程开始运行...
0 A
1 A
2 A
3 A
4 A
5 A
6 A
7 A
8 A
9 A
A线程结束运行...
B线程开始运行...
0 B
1 B
2 B
3 B
4 B
5 B
6 B
7 B
8 B
9 B
B线程结束运行...