-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathThreadTest.java
More file actions
71 lines (60 loc) · 1.52 KB
/
Copy pathThreadTest.java
File metadata and controls
71 lines (60 loc) · 1.52 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
package Thread;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class ThreadTest
{
public static void main(String[] args)
{
//1:继承Thread类创建线程
MyThread myThread = new MyThread();
myThread.start();
//2:实现Runnable接口创建线程
MyThread2 myThread2 = new MyThread2();
Thread thread = new Thread(myThread2);
thread.start();
//3:Callable任务借助FutureTask运行
CallableAndFutureTest();
}
private static void CallableAndFutureTest()
{
Callable<Integer> callable = new Callable<Integer>()
{
public Integer call() throws Exception
{
return new Random().nextInt(100);
}
};
FutureTask<Integer> future = new FutureTask<Integer>(callable);
new Thread(future).start();
try
{//可能做一些事情
Thread.sleep(5000);
System.out.println(future.get());
} catch (InterruptedException e)
{
e.printStackTrace();
} catch (ExecutionException e)
{
e.printStackTrace();
}
}
}
class MyThread2 implements Runnable
{
@Override
public void run()
{
System.out.println("sadfa");
}
}
class MyThread extends Thread
{
@Override
public void run()
{
super.run();
System.out.println("1322");
}
}