常见线程状态分析
wenking 7/26/2023 JVM
# 阻塞IO线程状态展示
java代码片段
- 服务端代码
public class NetworkServerTest {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(8087);
Socket accept = ss.accept();
InputStream is = accept.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
while (true) {
String s = br.readLine();
System.out.println(s);
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
- 客户端代码
public class NetworkClientTest {
public static void main(String[] args) throws IOException {
InetAddress addr = InetAddress.getByName("localhost");
Socket socket = new Socket(addr, 8087);
OutputStream os = socket.getOutputStream();
BufferedWriter br = new BufferedWriter(new OutputStreamWriter(os));
while (true) {
Scanner scanner = new Scanner(System.in);
String s = scanner.nextLine();
if (s.equals("$")) {
break;
}
br.write(s);
br.flush();
br.newLine();
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 阻塞读线程的状态为RUNNABLE
# IO输入流状态为TIMED_WAITING
java代码片段
- 服务端代码
服务端每隔 3 秒读一次io
public class NetworkServerTest {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(8087);
Socket accept = ss.accept();
InputStream is = accept.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
while (true) {
String s = br.readLine();
System.out.println(s);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
- 客户端代码
设置发送缓冲区大小为200个字节,客户端不断的发送 hello,world 字符串
public class NetworkClientTest {
public static void main(String[] args) throws IOException {
InetAddress addr = InetAddress.getByName("localhost");
Socket socket = new Socket(addr, 8087);
OutputStream os = socket.getOutputStream();
BufferedWriter br = new BufferedWriter(new OutputStreamWriter(os));
socket.setSendBufferSize(200);
while (true) {
br.write("hello, world");
br.flush();
br.newLine();
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 阻塞写线程的状态为RUNNABLE
客户端写线程的状态为RUNNABLE