forked from damaohongtu/JavaInterview
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathThreadTest.java
More file actions
75 lines (61 loc) · 1.9 KB
/
ThreadTest.java
File metadata and controls
75 lines (61 loc) · 1.9 KB
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package JavaBasic;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
/**
* @Classname ThreadTest
* @Description 多线程的三种实现方式
* @Date 19-7-22 上午9:30
* @Created by mao<tianmao818@qq.com>
*/
class MyThread1 extends Thread{
@Override
public void run(){
System.out.println(Thread.currentThread()+"thread by extends Thread");
}
}
class MyThread2 implements Runnable{
@Override
public void run(){
System.out.println(Thread.currentThread()+"thread by implements Runnable");
}
}
class MyThread3 implements Callable{
@Override
public String call() throws Exception{
return Thread.currentThread()+"thread by implements Callable";
}
}
public class ThreadTest {
public static void main(String[] args){
System.out.println(Thread.currentThread());
MyThread1 myThread1=new MyThread1();
myThread1.start();
MyThread2 myThread2=new MyThread2();
new Thread(myThread2).start();
FutureTask<String> futureTask=new FutureTask<>(new MyThread3());
new Thread(futureTask).start();
try {
String res=futureTask.get();
System.out.println(res);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
new Thread(()->{
System.out.println(Thread.currentThread()+"thread by lambda");
}).start();
new Thread() {
public void run() {
System.out.println(Thread.currentThread()+"thread by 1");
}
}.start();
Runnable r = new Runnable() {//创建方式2
public void run() {
System.out.println(Thread.currentThread()+"thread by 2");
}
};
new Thread(r).start();
}
}