java提供了三种方式创建线程,实现runnable接口、继承thread类、通过callable和future创建线程
runnable接口实现线程
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
33class RunnableThread implements Runnable {
String name = null;
public RunnableThread(String name){
this.name = name;
}
public void run(){
System.out.println("子线程run");
try {
for (int i = 5; i > 0; i--) {
System.out.println(this.name + ":" + i);
Thread.sleep(500);
}
}catch (InterruptedException e){
e.printStackTrace();
}
}
public void start(){
System.out.println(this.name + "开始执行");
Thread t = new Thread(this, this.name);
t.start();
}
}
public class test3 {
public static void main(String[] args){
RunnableThread th1 = new RunnableThread("thread1");
th1.start();
RunnableThread th2 = new RunnableThread("thread2");
th2.start();
}
}继承thread
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
33class InheritThread extends Thread{
String name = null;
public InheritThread(String name){
this.name = name;
}
public void run(){
System.out.println("子线程run");
try {
for (int i = 5; i > 0; i--) {
System.out.println(this.name + ":" + i);
Thread.sleep(500);
}
}catch (InterruptedException e){
e.printStackTrace();
}
}
public void start(){
System.out.println(this.name + "开始执行");
Thread t = new Thread(this, this.name);
t.start();
}
}
public class test3 {
public static void main(String[] args){
InheritThread th1 = new InheritThread("thread1");
th1.start();
InheritThread th2 = new InheritThread("thread2");
th2.start();
}
}实现callable
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
45
46
47
48import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ExecutionException;
class CallableThread implements Callable<Integer> {
String name = null;
public CallableThread(String name){
this.name = name;
}
public Integer call(){
System.out.println("子线程run");
try {
for (int i = 5; i > 0; i--) {
System.out.println(this.name + ":" + i);
Thread.sleep(500);
}
}catch (InterruptedException e){
e.printStackTrace();
}
return 1;
}
}
public class test3 {
public static void main(String[] args){
CallableThread c1 = new CallableThread("c1");
FutureTask<Integer> f1 = new FutureTask<>(c1);
new Thread(f1, "thread1").start();
CallableThread c2 = new CallableThread("c2");
FutureTask<Integer> f2 = new FutureTask<>(c2);
new Thread(f2, "thread2").start();
try{
System.out.println(f1.get());
System.out.println(f2.get());
}
catch (InterruptedException e)
{
e.printStackTrace();
} catch (ExecutionException e)
{
e.printStackTrace();
}
}
}