线程的三种实现方法

  线程的三种实现方法

继承Thread

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class extends Thread {
int i = 0;
public void run() {
super.run();
for (; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + " " + i);
}
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + " " + i);
}
new OneThread().start();
//主线程中
new OneThread().run();
}
}

实现Runnable接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class TwoThread implements Runnable {
int i = 0;
public void run() {
for (; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + " " + i);
}
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + " " + i);
}
TwoThread twoThread = new TwoThread();
new Thread(twoThread,"thread-a").start();
TwoThread twoThread1 = new TwoThread();
new Thread(twoThread1,"thread-b").start();
}
}

通过Callable和Future实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class ThreeThread implements Callable<Integer> {
public Integer call() throws Exception {
int i = 0;
for (; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + " " + i);
}
return i;
}
public static void main(String[] args) {
ThreeThread threeThread = new ThreeThread();
FutureTask<Integer> futureTask = new FutureTask<Integer>(threeThread);
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + " " + i);
}
new Thread(futureTask, "返回值的线程").start();
try {
System.out.println("线程返回值: " + futureTask.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}