Skip to content

Commit b7ade75

Browse files
author
wangyibing
committed
Merge branch 'master' into main
# Conflicts: # 01jvm/GCLogAnalysis.java # 01jvm/环境准备.txt # 02nio/nio01/src/main/java/java0/nio01/HttpServer02.java # 02nio/nio01/src/main/java/java0/nio01/HttpServer03.java # 02nio/nio02/pom.xml # 02nio/nio02/src/main/java/io/github/kimmking/gateway/NettyServerApplication.java # 02nio/nio02/src/main/java/io/github/kimmking/gateway/filter/HttpRequestFilter.java # 02nio/nio02/src/main/java/io/github/kimmking/gateway/inbound/HttpInboundHandler.java # 02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/netty4/NettyHttpClientOutboundHandler.java # 02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/okhttp/OkhttpOutboundHandler.java
1 parent e16d7bb commit b7ade75

File tree

7 files changed

+251
-36
lines changed

7 files changed

+251
-36
lines changed

02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/okhttp/OkhttpOutboundHandler.java

Lines changed: 3 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -31,10 +31,6 @@ public class OkhttpOutboundHandler {
3131

3232
public OkhttpOutboundHandler(String proxyServer) {
3333
this.proxyServer = proxyServer;
34-
// client = new OkHttpClient.Builder()
35-
// .readTimeout(100, TimeUnit.MILLISECONDS)
36-
// .connectTimeout(50, TimeUnit.MILLISECONDS)
37-
// .build();
3834
RejectedExecutionHandler policy = new ThreadPoolExecutor.CallerRunsPolicy();
3935
int cores = Runtime.getRuntime().availableProcessors() * 2;
4036
long keepAliveTime = 1000;
@@ -49,6 +45,7 @@ public void handle(FullHttpRequest fullRequest, ChannelHandlerContext ctx) {
4945
}
5046

5147
private void execute(ChannelHandlerContext ctx, String url, FullHttpRequest fullRequest) {
48+
// 创建OkHttpClient
5249
client = new OkHttpClient.Builder()
5350
.build();
5451
Request request = new Request.Builder().get().url(url).build();
@@ -68,6 +65,7 @@ private void handleResponse(ChannelHandlerContext ctx, Response response, FullHt
6865
if(response.isSuccessful()){
6966
try {
7067
String body = response.body().string();
68+
// 设置响应头
7169
httpResponse = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(body.getBytes()));
7270
httpResponse.headers().set("Content-Type", "application/json");
7371
httpResponse.headers().setInt("Content-Length", httpResponse.content().readableBytes());
@@ -81,14 +79,8 @@ private void handleResponse(ChannelHandlerContext ctx, Response response, FullHt
8179
ctx.write(httpResponse);
8280
}
8381
ctx.flush();
82+
ctx.close();
8483
}
8584
}
8685
}
87-
88-
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
89-
cause.printStackTrace();
90-
ctx.close();
91-
}
92-
93-
9486
}

03concurrency/01thread/src/main/java/com/github/thread/Homework03.java

Lines changed: 76 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -4,37 +4,17 @@
44

55
import java.util.concurrent.*;
66
import java.util.concurrent.atomic.AtomicInteger;
7+
import java.util.concurrent.locks.Condition;
8+
import java.util.concurrent.locks.LockSupport;
9+
import java.util.concurrent.locks.ReentrantLock;
710

811
/**
912
* 本周作业:(必做)思考有多少种方式,在main函数启动一个新线程或线程池,
1013
* 异步运行一个方法,拿到这个方法的返回值后,退出主线程?
1114
* 写出你的方法,越多越好,提交到github。
12-
* <p>
13-
* 一个简单的代码参考:
1415
*/
1516
public class Homework03 {
1617

17-
public static void main(String[] args) {
18-
19-
long start = System.currentTimeMillis();
20-
// 在这里创建一个线程或线程池,
21-
new Thread(new Runnable() {
22-
@Override
23-
public void run() {
24-
}
25-
}).start();
26-
// 异步执行 下面方法
27-
int result = sum(); //这是得到的返回值
28-
29-
// 确保 拿到result 并输出
30-
System.out.println("异步计算结果为:" + result);
31-
32-
System.out.println("使用时间:" + (System.currentTimeMillis() - start) + " ms");
33-
34-
// 然后退出main线程
35-
36-
}
37-
3818
/**
3919
* 使用join,子线程通过join确保执行
4020
*/
@@ -152,16 +132,87 @@ public void test06() {
152132
barrier.await();
153133
} catch (InterruptedException | BrokenBarrierException e) {
154134
e.printStackTrace();
155-
} finally {
156135
}
157136
System.out.println("异步计算结果为:" + atomicInteger.get());
158137

159138
}
160139

161-
//CyclicBarrier
140+
//LockSupport 阻塞1s
162141
@Test
163142
public void test07() {
143+
AtomicInteger atomicInteger = new AtomicInteger();
144+
Thread thread = new Thread(() -> {
145+
atomicInteger.set(sum());
146+
});
147+
thread.start();
148+
LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(1000));
149+
System.out.println("异步计算结果为:" + atomicInteger.get());
150+
}
151+
152+
//Condition 的等待通知方法
153+
@Test
154+
public void test08() {
155+
AtomicInteger atomicInteger = new AtomicInteger();
156+
ReentrantLock lock = new ReentrantLock();
157+
Condition condition = lock.newCondition();
158+
Thread thread = new Thread(() -> {
159+
lock.lock();
160+
atomicInteger.set(sum());
161+
try {
162+
condition.signal();
163+
} finally {
164+
lock.unlock();
165+
}
166+
});
167+
thread.start();
168+
lock.lock();
169+
try {
170+
condition.await();
171+
} catch (InterruptedException e) {
172+
e.printStackTrace();
173+
}
174+
System.out.println("异步计算结果为:" + atomicInteger.get());
175+
lock.unlock();
176+
}
164177

178+
//线程池+Future ,阻塞等待返回
179+
@Test
180+
public void test09() {
181+
ExecutorService executorService = Executors.newSingleThreadExecutor();
182+
Future<Integer> future = executorService.submit(new Callable<Integer>() {
183+
@Override
184+
public Integer call() throws Exception {
185+
return sum();
186+
}
187+
});
188+
try {
189+
System.out.println("异步计算结果为:" + future.get());
190+
} catch (InterruptedException e) {
191+
e.printStackTrace();
192+
} catch (ExecutionException e) {
193+
e.printStackTrace();
194+
}
195+
executorService.shutdown();
196+
}
197+
198+
199+
//semaphore 阻塞主线程,等待子线程执行完成释放
200+
@Test
201+
public void test10() {
202+
Semaphore semaphore = new Semaphore(0);
203+
AtomicInteger integer = new AtomicInteger();
204+
new Thread(() -> {
205+
integer.set(sum());
206+
// 子线程执行完成,释放
207+
semaphore.release();
208+
}).start();
209+
try {
210+
// 信号量为0,阻塞
211+
semaphore.acquire();
212+
} catch (InterruptedException e) {
213+
e.printStackTrace();
214+
}
215+
System.out.println("异步计算结果为:" + integer.get());
165216
}
166217

167218
private static int sum() {
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<project xmlns="http://maven.apache.org/POM/4.0.0"
3+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
5+
<modelVersion>4.0.0</modelVersion>
6+
7+
<groupId>org.github</groupId>
8+
<artifactId>01threadpool</artifactId>
9+
<version>1.0-SNAPSHOT</version>
10+
<dependencies>
11+
<dependency>
12+
<groupId>junit</groupId>
13+
<artifactId>junit</artifactId>
14+
<version>4.12</version>
15+
</dependency>
16+
</dependencies>
17+
18+
</project>
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
package com.github.threadpool;
2+
3+
import org.junit.Test;
4+
5+
import java.util.ArrayList;
6+
import java.util.Collection;
7+
import java.util.Collections;
8+
import java.util.List;
9+
import java.util.concurrent.locks.Lock;
10+
import java.util.concurrent.locks.ReentrantLock;
11+
12+
public class FairAndUnfairTest {
13+
private static Lock fairLock = new ReentrantLock2(true);
14+
private static Lock unfairLock = new ReentrantLock2(false);
15+
16+
@Test
17+
public void fair(){
18+
testLock(fairLock);
19+
}
20+
21+
@Test
22+
public void unfair(){
23+
testLock(unfairLock);
24+
}
25+
26+
private void testLock(Lock lock){
27+
for (int i = 0; i < 5; i++) {
28+
new Job(lock).start();
29+
}
30+
}
31+
private static class Job extends Thread{
32+
private ReentrantLock2 lock;
33+
public Job(Lock lock){
34+
this.lock = (ReentrantLock2) lock;
35+
}
36+
37+
@Override
38+
public void run() {
39+
lock.lock();
40+
System.out.println(Thread.currentThread().getName()+","+lock.getQueuedTreads());
41+
System.out.println(Thread.currentThread().getName()+","+lock.getQueuedTreads());
42+
lock.unlock();
43+
}
44+
}
45+
46+
private static class ReentrantLock2 extends ReentrantLock{
47+
public ReentrantLock2(boolean fair){
48+
super(fair);
49+
}
50+
51+
public Collection<Thread> getQueuedTreads(){
52+
List<Thread> arrayList = new ArrayList<Thread>(super.getQueuedThreads());
53+
Collections.reverse(arrayList);
54+
return arrayList;
55+
}
56+
}
57+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package com.github.threadpool;
2+
3+
public class Singleton {
4+
private volatile static Singleton instance;
5+
6+
public static Singleton getInstance() {
7+
if (instance == null) {
8+
synchronized (Singleton.class) {
9+
if (instance == null) {
10+
instance = new Singleton();
11+
}
12+
}
13+
}
14+
return instance;
15+
}
16+
17+
public static void main(String[] args) {
18+
Singleton.getInstance();
19+
}
20+
}
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package com.github.threadpool;
2+
3+
import java.util.concurrent.ArrayBlockingQueue;
4+
import java.util.concurrent.ThreadFactory;
5+
import java.util.concurrent.ThreadPoolExecutor;
6+
import java.util.concurrent.TimeUnit;
7+
8+
public class ThreadPool01 {
9+
public static void main(String[] args) {
10+
ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(5,
11+
6,
12+
0,
13+
TimeUnit.MILLISECONDS,
14+
new ArrayBlockingQueue<Runnable>(1),
15+
new ThreadFactory() {
16+
@Override
17+
public Thread newThread(Runnable r) {
18+
return new Thread(r);
19+
}
20+
},
21+
new ThreadPoolExecutor.AbortPolicy());
22+
MyTask task = new MyTask();
23+
for (int i = 0; i < 100; i++) {
24+
try {
25+
poolExecutor.execute(task);
26+
} catch (Exception e) {
27+
e.printStackTrace();
28+
poolExecutor.shutdown();
29+
}
30+
}
31+
poolExecutor.shutdown();
32+
}
33+
34+
}
35+
36+
class MyTask implements Runnable {
37+
private int count = 0;
38+
private static final int MAXVALUE = 1000;
39+
40+
@Override
41+
public void run() {
42+
for (int i = 0; i < MAXVALUE; i++) {
43+
System.out.println(++count);
44+
}
45+
}
46+
}
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package com.github.threadpool;
2+
3+
/*** volatile变量自增运算测试 ** @author zzm */
4+
public class VolatileTest {
5+
public static volatile int race = 0;
6+
7+
public static void increase() {
8+
race++;
9+
}
10+
11+
private static final int THREADS_COUNT = 20;
12+
13+
public static void main(String[] args) {
14+
Thread[] threads = new Thread[THREADS_COUNT];
15+
for (int i = 0; i < THREADS_COUNT; i++) {
16+
threads[i] = new Thread(new Runnable() {
17+
@Override
18+
public void run() {
19+
for (int i = 0; i < 10000; i++) {
20+
increase();
21+
}
22+
}
23+
});
24+
threads[i].start();
25+
}
26+
// 等待所有累加线程都结束
27+
while (Thread.activeCount() > 1)
28+
Thread.yield();
29+
System.out.println(race);
30+
}
31+
}

0 commit comments

Comments
 (0)