第4章 Java并发编程基础

查看JVM线程信息

居然还有这么好的东西

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package chapter04;

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;

/**
* Created by hero on 17-3-14.
*/
public class MultiThread {

public static void main(String[] args) {
MultiThread.showThreadsInfo(true, true);
}

public static void showThreadsInfo(boolean lockedMonitors, boolean lockedSynchronizers) {
ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
ThreadInfo[] threadInfos = threadMXBean.dumpAllThreads(lockedMonitors, lockedSynchronizers);
for (ThreadInfo threadInfo : threadInfos) {
System.out.println("[" + threadInfo.getThreadId() + "] " + threadInfo.getThreadName());
}
}
}

线程优先级靠谱吗

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
package chapter04;

import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;

/**
* Created by hero on 17-3-14.
*/
public class ThreadPriority {
public static final int _SIZE = 10;
private volatile boolean isEnd;
private CyclicBarrier cyclicBarrier;

public ThreadPriority() {
cyclicBarrier = new CyclicBarrier(_SIZE);
isEnd = false;
}

public static void main(String[] args) {
ThreadPriority threadPriority = new ThreadPriority();
threadPriority.run();
}

public void run() {
Job[] jobs = new Job[_SIZE];
for (int i = 0; i < _SIZE; i++) {
int priority = i < 5 ? Thread.MIN_PRIORITY : Thread.MAX_PRIORITY;
jobs[i] = new Job(priority);
Thread thread = new Thread(jobs[i]);
thread.setPriority(priority);
thread.start();
}

try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}

isEnd = true;

for (Job job : jobs) {
System.out.printf("%5d %15d\n", job.priority, job.count);
}
}

private class Job implements Runnable {
private int priority;
private int count;

public Job(int priority) {
this.priority = priority;
this.count = 0;
}

public void run() {
try {
cyclicBarrier.await();
while (!isEnd) {
this.count++;
Thread.yield();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

很显然,你需要运行一下上面的代码。

线程的状态

state 说明
NEW 初始状态,线程被构建,但还没调start()
RUNNABLE 运行状态,Java将操作系统中的就绪和运行中两种状态笼统称为“RUNNABLE”
BLOCKED 阻塞状态,表示线程阻塞于锁
WAITING 等待状态,需要等待其它线程做出一些特定操作(通知或中断)
TIME_WAITING 超时等待,不同于WAITING,它可以在指定时间后自行返回
TERMINATED 终止状态,线程执行完毕

继续阅读全文 »