forked from bage2014/study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreadImp.java
More file actions
91 lines (71 loc) · 1.78 KB
/
Copy pathThreadImp.java
File metadata and controls
91 lines (71 loc) · 1.78 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package com.bage.study.java.multhread;
/**
* 多线程实现
* @author bage
*
*/
public class ThreadImp {
public static final int count = 10;
public static void main(String[] args) throws Exception {
// 实现方式
thread1();
thread2();
// 线程的状态
// NEW
// A thread that has not yet started is in this state.
// •RUNNABLE
// A thread executing in the Java virtual machine is in this state.
// •BLOCKED
// A thread that is blocked waiting for a monitor lock is in this state.
// •WAITING
// A thread that is waiting indefinitely for another thread to perform a particular action is in this state.
// •TIMED_WAITING
// A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state.
// •TERMINATED
// A thread that has exited is in this state.
}
private static void thread2() {
Thread2 myThread = new Thread2();
Thread thread = new Thread(myThread);
thread.start();
}
private static void thread1() throws Exception {
Thread thread = new Thread1();
System.out.println(thread.getState());
thread.start();
}
}
/**
* 继承 Thread 类
* @author bage
*
*/
class Thread1 extends Thread{
@Override
public void run() {
for (int i = 0; i < ThreadImp.count; i++) {
System.out.println("thread1" + i);
try {
Thread.sleep(1000);
System.out.println(getState());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(getState());
System.out.println("thread1" + i);
}
}
}
/**
* 实现 Runnable 接口
* @author bage
*
*/
class Thread2 implements Runnable{
public void run() {
for (int i = 0; i < ThreadImp.count; i++) {
System.out.println("thread2" + i);
}
}
}