8000 自己修改的 · JavaCourse00/JavaCourseCodes@22444af · GitHub
[go: up one dir, main page]

Skip to content

Commit 22444af

Browse files
author
v-yanb07
committed
自己修改的
1 parent 436102c commit 22444af

File tree

13 files changed

+154
-58
lines changed

13 files changed

+154
-58
lines changed

02nio/nio01/src/main/java/java0/nio01/HttpServer03.java

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package java0.nio01;
22

33
import java.io.IOException;
4+
import java.io.InputStream;
45
import java.io.PrintWriter;
56
import java.net.ServerSocket;
67
import java.net.Socket;
@@ -9,8 +10,8 @@
910

1011
public class HttpServer03 {
1112
public static void main(String[] args) throws IOException{
12-
ExecutorService executorService = Executors.newFixedThreadPool(40);
13-
final ServerSocket serverSocket = new ServerSocket(8803);
13+
ExecutorService executorService = Executors.newFixedThreadPool(20);
14+
final ServerSocket serverSocket = new ServerSocket(8088);
1415
while (true) {
1516
try {
1617
final Socket socket = serverSocket.accept();
@@ -23,11 +24,18 @@ public static void main(String[] args) throws IOException{
2324

2425
private static void service(Socket socket) {
2526
try {
27+
InputStream in = socket.getInputStream();
28+
byte[] buf = new byte[1024];
29+
in.read(buf);
30+
System.out.println("request from client " + socket.getInetAddress().getHostAddress());
31+
32+
System.out.println(new String(buf));
33+
2634
Thread.sleep(20);
2735
PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
2836
printWriter.println("HTTP/1.1 200 OK");
2937
printWriter.println("Content-Type:text/html;charset=utf-8");
30-
String body = "hello,nio";
38+
String body = new String(buf);
3139
printWriter.println("Content-Length:" + body.getBytes().length);
3240
printWriter.println();
3341
printWriter.write(body);
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package io.github.kimmking.gateway.filter;
2+
3+
import io.netty.channel.ChannelHandlerContext;
4+
import io.netty.handler.codec.http.FullHttpRequest;
5+
import io.netty.handler.codec.http.HttpHeaders;
6+
7+
public class HttpRequestFilterImpl implements HttpRequestFilter {
8+
9+
@Override
10+
public void filter(FullHttpRequest fullRequest,ChannelHandlerContext ctx){
11+
fullRequest.headers().add("NIO","yanbing");
12+
13+
}
14+
}

02nio/nio02/src/main/java/io/github/kimmking/gateway/inbound/HttpInboundHandler.java

Lines changed: 33 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,24 @@
11
package io.github.kimmking.gateway.inbound;
22

33
import io.github.kimmking.gateway.outbound.httpclient4.HttpOutboundHandler;
4+
import io.netty.buffer.Unpooled;
5+
import io.netty.channel.ChannelFutureListener;
46
import io.netty.channel.ChannelHandlerContext;
57
import io.netty.channel.ChannelInboundHandlerAdapter;
8+
import io.netty.handler.codec.http.DefaultFullHttpResponse;
69
import io.netty.handler.codec.http.FullHttpRequest;
10+
import io.netty.handler.codec.http.FullHttpResponse;
11+
import io.netty.handler.codec.http.HttpUtil;
712
import io.netty.util.ReferenceCountUtil;
813
import org.slf4j.Logger;
914
import org.slf4j.LoggerFactory;
1015

16+
import static io.netty.handler.codec.http.HttpHeaderValues.KEEP_ALIVE;
17+
import static io.netty.handler.codec.http.HttpResponseStatus.NO_CONTENT;
18+
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
19+
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
20+
import static org.apache.http.HttpHeaders.CONNECTION;
21+
1122
public class HttpInboundHandler extends ChannelInboundHandlerAdapter {
1223

1324
private static Logger logger = LoggerFactory.getLogger(HttpInboundHandler.class);
@@ -44,28 +55,28 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) {
4455
}
4556
}
4657

47-
// private void handlerTest(FullHttpRequest fullRequest, ChannelHandlerContext ctx) {
48-
// FullHttpResponse response = null;
49-
// try {
50-
// String value = "hello,kimmking";
51-
// response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(value.getBytes("UTF-8")));
52-
// response.headers().set("Content-Type", "application/json");
53-
// response.headers().setInt("Content-Length", response.content().readableBytes());
54-
//
55-
// } catch (Exception e) {
56-
// logger.error("处理测试接口出错", e);
57-
// response = new DefaultFullHttpResponse(HTTP_1_1, NO_CONTENT);
58-
// } finally {
59-
// if (fullRequest != null) {
60-
// if (!HttpUtil.isKeepAlive(fullRequest)) {
61-
// ctx.write(response).addListener(ChannelFutureListener.CLOSE);
62-
// } else {
63-
// response.headers().set(CONNECTION, KEEP_ALIVE);
64-
// ctx.write(response);
65-
// }
66-
// }
67-
// }
68-
// }
58+
private void handlerTest(FullHttpRequest fullRequest, ChannelHandlerContext ctx) {
59+
FullHttpResponse response = null;
60+
try {
61+
String value = "hello,kimmking";
62+
response = new DefaultFullHttpResponse (HTTP_1_1, OK, Unpooled.wrappedBuffer(value.getBytes("UTF-8")));
63+
response.headers().set("Content-Type", "application/json");
64+
response.headers().setInt("Content-Length", response.content().readableBytes());
65+
66+
} catch (Exception e) {
67+
logger.error("处理测试接口出错", e);
68+
response = new DefaultFullHttpResponse(HTTP_1_1, NO_CONTENT);
69+
} finally {
70+
if (fullRequest != null) {
71+
if (!HttpUtil.isKeepAlive(fullRequest)) {
72+
ctx.write(response).addListener( ChannelFutureListener.CLOSE);
73+
} else {
74+
response.headers().set(CONNECTION, KEEP_ALIVE);
75+
ctx.write(response);
76+
}
77+
}
78+
}
79+
}
6980
//
7081
// @Override
7182
// public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {

02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/httpclient4/HttpOutboundHandler.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package io.github.kimmking.gateway.outbound.httpclient4;
22

33

4+
import io.github.kimmking.gateway.filter.HttpRequestFilterImpl;
45
import io.netty.buffer.Unpooled;
56
import io.netty.channel.ChannelFutureListener;
67
import io.netty.channel.ChannelHandlerContext;
@@ -63,10 +64,12 @@ private void fetchGet(final FullHttpRequest inbound, final ChannelHandlerContext
6364
final HttpGet httpGet = new HttpGet(url);
6465
//httpGet.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE);
6566
httpGet.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE);
67+
httpGet.setHeader("yanbing","headers");
6668
httpclient.execute(httpGet, new FutureCallback<HttpResponse>() {
6769
@Override
6870
public void completed(final HttpResponse endpointResponse) {
6971
try {
72+
new HttpRequestFilterImpl().filter(inbound,ctx);
7073
handleResponse(inbound, ctx, endpointResponse);
7174
} catch (Exception e) {
7275
e.printStackTrace();

03concurrency/0301/src/main/java/java0/conc0301/sync/Counter.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
package java0.conc0301.sync;
22

33
public class Counter {
4-
4+
55
public final static int A=10;
6-
6+
77
public static int B=10;
8-
8+
99
private volatile int sum = 0;
1010
public synchronized void incr() {
1111
sum=sum+1;

03concurrency/0301/src/main/java/java0/conc0302/lock/ConditionDemo.java

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,13 @@ public void put(Object x) throws InterruptedException {
1616
lock.lock();
1717
try {
1818
// 当count等于数组的大小时,当前线程等待,直到notFull通知,再进行生产
19-
while (count == items.length)
19+
while (count == items.length) {
2020
notFull.await();
21+
}
2122
items[putptr] = x;
22-
if (++putptr == items.length) putptr = 0;
23+
if (++putptr == items.length) {
24+
putptr = 0;
25+
}
2326
++count;
2427
notEmpty.signal();
2528
} finally {

03concurrency/0301/src/main/java/java0/conc0302/lock/ReentrantLockDemo.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,15 +6,15 @@ public class ReentrantLockDemo {
66
public static void main(String[] args) {
77
final Count count = new Count();
88

9-
for (int i = 0; i < 2; i++) {
9+
for (int i = 0; i < 5; i++) {
1010
new Thread() {
1111
public void run() {
1212
count.get();
1313
}
1414
}.start();
1515
}
1616

17-
for (int i = 0; i < 2; i++) {
17+
for (int i = 0; i < 4; i++) {
1818
new Thread() {
1919
public void run() {
2020
count.put();

03concurrency/0301/src/main/java/java0/conc0302/lock/ReentrantReadWriteLockDemo2.java

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
import java.util.HashMap;
55
import java.util.Map;
6+
import java.util.concurrent.locks.ReentrantLock;
67
import java.util.concurrent.locks.ReentrantReadWriteLock;
78

89
public class ReentrantReadWriteLockDemo2 {
@@ -12,7 +13,11 @@ public class ReentrantReadWriteLockDemo2 {
1213
private final ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
1314

1415
public Object readWrite(String key) {
16+
ReentrantLock lock = new ReentrantLock();
17+
lock.lock();
1518
Object value = null;
19+
lock.unlock();
20+
1621
System.out.println("1.首先开启读锁去缓存中取数据");
1722
rwLock.readLock().lock();
1823
try {

03concurrency/0301/src/main/java/java0/conc0303/Homework03.java

Lines changed: 60 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
11
package java0.conc0303;
22

3+
import java0.conc0303.tool.CountDownLatchDemo;
4+
5+
import java.util.Random;
6+
import java.util.concurrent.*;
7+
38
/**
49
* 本周作业:(必做)思考有多少种方式,在main函数启动一个新线程或线程池,
510
* 异步运行一个方法,拿到这个方法的返回值后,退出主线程?
@@ -9,24 +14,69 @@
914
*/
1015
public class Homework03 {
1116

12-
public static void main(String[] args) {
13-
17+
public static void main(String[] args) throws InterruptedException, ExecutionException{
1418
long start=System.currentTimeMillis();
15-
// 在这里创建一个线程或线程池,
1619
// 异步执行 下面方法
17-
18-
int result = sum(); //这是得到的返回值
19-
20+
// Integer result = method01();
21+
22+
// Integer result = method02();
23+
24+
// Integer result = mothod03();
2025
// 确保 拿到result 并输出
26+
Integer result = method04();
27+
2128
System.out.println("异步计算结果为:"+result);
22-
2329
System.out.println("使用时间:"+ (System.currentTimeMillis()-start) + " ms");
24-
2530
// 然后退出main线程
2631
}
27-
32+
33+
private static Integer method04() throws InterruptedException, ExecutionException{
34+
ExecutorService executor = Executors.newCachedThreadPool();
35+
Future<Integer> call = executor.submit(new Callable<Integer>() {
36+
@Override
37+
public Integer call() throws Exception {
38+
return sum();
39+
}
40+
});
41+
Integer result = call.get();
42+
executor.shutdown();
43+
return result;
44+
}
45+
46+
private static Integer mothod03() throws InterruptedException, ExecutionException{
47+
ExecutorService executor = Executors.newSingleThreadExecutor();
48+
FutureTask<Integer> task = new FutureTask<Integer>(new Callable<Integer>() {
49+
@Override
50+
public Integer call() throws Exception {
51+
return sum();
52+
}
53+
});
54+
executor.submit(task);
55+
return task.get();
56+
}
57+
58+
private static Integer method02() throws InterruptedException, ExecutionException{
59+
FutureTask<Integer> task = new FutureTask<Integer>(new Callable<Integer>() {
60+
@Override
61+
public Integer call() throws Exception {
62+
return sum();
63+
}
64+
});
65+
new Thread(task).start();
66+
return task.get();
67+
}
68+
69+
70+
private static Integer method01(){
71+
return (Integer) CompletableFuture.supplyAsync(() -> {
72+
return sum();
73+
}).join();
74+
}
75+
76+
77+
2878
private static int sum() {
29-
return fibo(36);
79+
return fibo(35);
3080
}
3181

3282
private static int fibo(int a) {

03concurrency/0301/src/main/java/java0/conc0303/collection/CopyOnWriteArrayListDemo.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,11 +13,11 @@ public static void main(String[] args) {
1313
// ArrayList,LinkedList,Vector不安全,运行报错
1414
// why Vector 也不安全
1515
// List<Integer> list = new ArrayList<Integer>();
16-
// List<Integer> list = new LinkedList<>();
16+
List<Integer> list = new LinkedList<>();
1717
// List<Integer> list = new Vector<>();
1818

1919
// 只有CopyOnWriteArrayList 安全,不报错
20-
List<Integer> list = new CopyOnWriteArrayList();
20+
// List<Integer> list = new CopyOnWriteArrayList();
2121

2222
for (int i = 0; i < 10000; i++)
2323
{

0 commit comments

Comments
 (0)
0