本文实例为大家分享了Java实现多线程的三种方式,供大家参考,具体内容如下
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
public class Main {
public static void main(String[] args) {
//方法一:继承Thread
int i = 0 ;
// for(; i < 100; i++){ // System.out.println(Thread.currentThread().getName() + " " + i); // if (i == 5) { // ThreadExtendsThread threadExtendsThread = new ThreadExtendsThread(); // threadExtendsThread.start(); // } // } //方法二:实现Runnable
// for(i = 0; i < 100; i++){ // System.out.println(Thread.currentThread().getName() + " " + i); // if (i == 5) { // Runnable runnable = new ThreadImplementsRunnable(); // new Thread(runnable).start(); // new Thread(runnable).start(); // } // } //方法三:实现Callable接口
Callable<Integer> callable = new ThreadImplementsCallable();
FutureTask<Integer> futureTask = new FutureTask<>(callable);
for (i = 0 ; i < 100 ; i++){
System.out.println(Thread.currentThread().getName() + " " + i);
if (i == 5 ) {
new Thread(futureTask).start();
new Thread(futureTask).start();
}
}
try {
System.out.println( "futureTask ruturn: " + futureTask.get());
} catch (Exception e) {
e.printStackTrace();
}
}
} |
方法一,继承自Thread
1
2
3
4
5
6
7
8
9
|
public class ThreadExtendsThread extends Thread {
private int i;
@Override
public void run() {
for (; i < 100 ; i++) {
System.out.println(getName() + " " + i);
}
}
} |
run方法为线程执行体,ThreadExtendsThread对象即为线程对象。
方法二,实现Runnable接口
1
2
3
4
5
6
7
8
9
|
public class ThreadImplementsRunnable implements Runnable {
private int i;
@Override
public void run() {
for (; i < 100 ; i++){
System.out.println(Thread.currentThread().getName() + " " + i);
}
}
} |
run方法为线程执行体,使用时New一个Thread对象,Runnable对象作为target传递给Thread对象。且同一个Runnable对象可作为多个Thread的target,这些线程均共享Runnable对象的实例变量。
方法三,实现Callable接口
1
2
3
4
5
6
7
8
9
10
11
12
13
|
import java.util.concurrent.Callable;
public class ThreadImplementsCallable implements Callable<Integer> {
private int i;
@Override
public Integer call() throws Exception {
for (; i < 100 ; i++){
System.out.println(Thread.currentThread().getName() + " " + i);
}
return i;
}
} |
Callable接口类似于Runnable接口,但比对方强大,线程执行体为call方法,该方法具有返回值和可抛出异常。使用时将Callable对象包装为FutureTask对象,通过泛型指定返回值类型。可稍候调用FutureTask的get方法取回执行结果。
以上就是本文的全部内容,希望对大家的学习有所帮助。