Skip to content

Commit fe66f70

Browse files
committed
Thread.aliveCount()的生命周期和Thread的生命周期一致
1 parent f7a21bc commit fe66f70

File tree

3 files changed

+97
-1
lines changed

3 files changed

+97
-1
lines changed

JavaMultiThreadingCodes/src/JoiningAndSynchronizeThreads_3/Worker.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ public void run() {
7777
thread1.join(); //主线程等待子线程执行完后在执行下面的sysout
7878
thread2.join();
7979
} catch (InterruptedException ignored) {
80-
80+
ignored.printStackTrace();
8181
}
8282
System.out.println("Count is: " + count); //用join保证保证前面两个线程已经执行完成
8383
}
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package mytest_0;
2+
3+
/**
4+
* @author liwen.
5+
* @date 2016/7/20 18:05.
6+
*/
7+
public class ThreadActiveCount {
8+
9+
public static void main(String[] args) {
10+
MyThread my = new MyThread();
11+
MyThread my2 = new MyThread();
12+
Thread t1 = new Thread(my);
13+
Thread t2 = new Thread(my);
14+
Thread t3 = new Thread(my);
15+
Thread t4 = new Thread(my2);
16+
t1.start();
17+
t2.start();
18+
t3.start();
19+
t4.start();
20+
21+
Thread[] threads = new Thread[Thread.activeCount()]; //默认会有两个线程,一个main线程,一个monitor线程
22+
int i = Thread.enumerate(threads);
23+
System.out.println(i);
24+
25+
for(Thread t:threads){
26+
System.out.println("hello:"+t.getName());
27+
}
28+
29+
// t1.start();
30+
// t2.start();
31+
// t3.start();
32+
// t4.start();
33+
34+
}
35+
}
36+
37+
class MyThread implements Runnable{
38+
39+
@Override
40+
public void run() {
41+
System.out.println(Thread.currentThread().getName());
42+
}
43+
}
44+
45+
/**
46+
* Thread.activeCount()计算值和线程的生命周期不一样,当线程一旦创建即使还未调用start(),会出现在activeCount中(from java-thread book) ---- 这是错误的
47+
* 线程只有调用了start()方法,才会出现在activeCount中;只会显示该程序启动所用到的线程,不会显示虚拟机中的其他线程(如:垃圾回收线程)
48+
* 一个线程实例只能启动一次
49+
*/
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package mytest_0;
2+
3+
/**
4+
* @author liwen.
5+
* @date 2016/7/20 17:30.
6+
*/
7+
public class ThreadGetName extends Thread{
8+
9+
TestThread testThread;
10+
11+
public ThreadGetName(TestThread test) {
12+
super("mytest222");
13+
this.testThread=test;
14+
}
15+
16+
public static void main(String[] args) {
17+
TestThread test = new TestThread();
18+
test.setName("mytest111");
19+
test.start();
20+
new ThreadGetName(test).start();
21+
}
22+
23+
@Override
24+
public void run() {
25+
System.out.println("hello javaThread");
26+
}
27+
28+
}
29+
30+
class TestThread extends Thread{
31+
32+
public String getResult(){
33+
String name = Thread.currentThread().getName();
34+
if(name.startsWith("mytest")){
35+
String result = name + "---hello";
36+
System.out.println(result);
37+
return result;
38+
} else{
39+
return "";
40+
}
41+
}
42+
43+
@Override
44+
public void run() {
45+
getResult();
46+
}
47+
}

0 commit comments

Comments
 (0)