1、Java中建立線程方法java
1. 繼承Thread類建立線程類
定義Thread類的子類,重寫該類的run()方法。該方法爲線程執行體。 建立Thread子類的實例。即線程對象。 調用線程對象的start()方法啓動該線程,示例代碼以下:編程
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
public
class
ThreadTest extends Thread{
int
i = 0;
//重寫run方法,run方法的方法體就是現場執行體
public
void
run() {
for
(;i<10;i++){
System.
out
.println(i);
}
}
public
static
void
main(String[] args) {
for
(
int
i = 0;i< 10;i++) {
System.
out
.println(Thread.currentThread().getName()+
" : "
+i);
new
ThreadTest().start();
}
}
}
|
1
2
3
4
5
6
7
8
|
// 或者
public
static
void
main(String[] args) {
for
(
int
i = 0;i< 10;i++) {
new
Thread(){
public
void
run() {
System.
out
.println(Thread.currentThread().getName());
}.start();
}
}
|
2. 實現Runnable接口建立線程類
定義Runnable接口的實現類,重寫該接口的run()方法。該方法爲線程執行體。 建立Runnable實現類的實例。並以此實例做爲Thread的target來建立Thread對象。該Thread對象纔是真正的線程對象。 調用線程對象(該Thread對象)的start()方法啓動該線程。多線程
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
public
class
RunnableThreadTest implements Runnable {
public
void
run() {
for
(
int
i = 0;i <10;i++) {
System.
out
.println(Thread.currentThread().getName()+
" "
+i);
}
}
public
static
void
main(String[] args) {
for
(
int
i = 0;i < 100;i++) {
System.
out
.println(Thread.currentThread().getName()+
" "
+i);
RunnableThreadTest rtt =
new
RunnableThreadTest();
new
Thread(rtt,
"新線程1"
).start();
}
}
}
|
1
2
3
4
5
6
7
8
9
10
|
// 或者
public
static
void
main(String[] args) {
for
(
int
i = 0;i < 100;i++) {
new
Thread(
new
Runnable() {
public
void
run() {
System.
out
.println(Thread.currentThread().getName());
}
}).start();
}
}
|
3. 使用Callable和Future建立線程併發
示例代碼以下:ide
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
|
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public
class
CallableThreadTest implements Callable<Integer> {
public
static
void
main(String[] args) {
CallableThreadTest ctt =
new
CallableThreadTest();
FutureTask<Integer> ft =
new
FutureTask<>(ctt);
for
(
int
i = 0;i < 10;i++) {
System.
out
.println(Thread.currentThread().getName()+
" 的循環變量i的值"
+i);
if
(i==5) {
new
Thread(ft,
"有返回值的線程"
).start();
}
}
try
{
System.
out
.println(
"子線程的返回值:"
+ft.
get
());
}
catch
(InterruptedException e) {
e.printStackTrace();
}
catch
(ExecutionException e) {
e.printStackTrace();
}
}
@Override
public
Integer call() throws Exception {
int
i=0;
for
(;i<100;i++) {
System.
out
.println(Thread.currentThread().getName()+
" "
+i);
}
return
i;
}
}
|
2、建立線程的三種方式的對比this
三種方法建立線程各有優劣spa
1.採用實現Runnable、Callable接口的方式創見多線程.net
優點:線程
劣勢:code
2.使用繼承Thread類的方式建立多線程
優點:
劣勢:
參考文章:
1. java 併發