├── .gitignore ├── pom.xml └── src ├── main ├── java │ └── com │ │ ├── JVM │ │ ├── heap │ │ │ └── HeapGCTest.java │ │ ├── perm │ │ │ └── PermGengc.java │ │ └── stack │ │ │ ├── StackGCTest.java │ │ │ ├── TestStack.java │ │ │ └── WordReuseTest.java │ │ ├── NIO │ │ ├── core │ │ │ ├── BufferTest.java │ │ │ └── ChannelTest.java │ │ ├── netty │ │ │ ├── Http │ │ │ │ └── fileServer │ │ │ │ │ ├── HttpFileServer.java │ │ │ │ │ └── HttpFileServerHandler.java │ │ │ ├── base │ │ │ │ ├── TimeClient.java │ │ │ │ ├── TimeClientHandler.java │ │ │ │ ├── TimeServer.java │ │ │ │ └── TimerServerHandler.java │ │ │ ├── frameDecoder │ │ │ │ ├── DelimiterBasedFrameDecoder │ │ │ │ │ ├── EchoClient.java │ │ │ │ │ ├── EchoClientHandler.java │ │ │ │ │ ├── EchoServer.java │ │ │ │ │ └── EchoServerHandler.java │ │ │ │ └── FixedLengthFrameDecoder │ │ │ │ │ ├── EchoServer.java │ │ │ │ │ └── EchoServerHandler.java │ │ │ └── tcpIP │ │ │ │ ├── NotStickers │ │ │ │ ├── TimeClient.java │ │ │ │ ├── TimeClientHandler.java │ │ │ │ ├── TimeServer.java │ │ │ │ └── TimerServerHandler.java │ │ │ │ └── stickers │ │ │ │ ├── TimeClient.java │ │ │ │ ├── TimeClientHandler.java │ │ │ │ ├── TimeServer.java │ │ │ │ └── TimerServerHandler.java │ │ └── nio │ │ │ └── _1 │ │ │ ├── MultiplexerTimerServer.java │ │ │ └── TimeClientHandle.java │ │ ├── javaCore │ │ ├── java_thread │ │ │ ├── JUC │ │ │ │ ├── Atomic │ │ │ │ │ ├── AtomicIntegerArrayTest.java │ │ │ │ │ ├── AtomicIntegerTest.java │ │ │ │ │ └── AtomicReferenceTest.java │ │ │ │ ├── CAS │ │ │ │ │ └── Counter.java │ │ │ │ ├── Lock │ │ │ │ │ ├── AQS │ │ │ │ │ │ ├── Mutex.java │ │ │ │ │ │ └── twinsLock │ │ │ │ │ │ │ ├── TwinsLock.java │ │ │ │ │ │ │ └── TwinsLockTest.java │ │ │ │ │ ├── ReentrantLock │ │ │ │ │ │ └── _1 │ │ │ │ │ │ │ ├── Job.java │ │ │ │ │ │ │ ├── PrintQueue.java │ │ │ │ │ │ │ └── Test.java │ │ │ │ │ ├── ReentrantReadWriteLock │ │ │ │ │ │ ├── PricesInfo.java │ │ │ │ │ │ ├── Reader.java │ │ │ │ │ │ ├── Test.java │ │ │ │ │ │ └── Writer.java │ │ │ │ │ └── condition │ │ │ │ │ │ ├── Customer.java │ │ │ │ │ │ ├── Depot.java │ │ │ │ │ │ ├── Producer.java │ │ │ │ │ │ └── Test.java │ │ │ │ ├── ThreadUtils │ │ │ │ │ ├── CountDownLatch │ │ │ │ │ │ ├── Conference.java │ │ │ │ │ │ ├── Participater.java │ │ │ │ │ │ └── Test.java │ │ │ │ │ ├── CyclicBarrier │ │ │ │ │ │ ├── CyclicBarrierTest_1.java │ │ │ │ │ │ └── CyclicBarrierTest_2.java │ │ │ │ │ ├── Exchanger │ │ │ │ │ │ ├── Consumer.java │ │ │ │ │ │ ├── Producer.java │ │ │ │ │ │ └── Test.java │ │ │ │ │ ├── Phaser │ │ │ │ │ │ ├── PhaserTest_1.java │ │ │ │ │ │ ├── PhaserTest_2.java │ │ │ │ │ │ ├── PhaserTest_3.java │ │ │ │ │ │ ├── PhaserTest_4.java │ │ │ │ │ │ ├── PhaserTest_5.java │ │ │ │ │ │ ├── PhaserTest_6.java │ │ │ │ │ │ └── PhaserTest_7.java │ │ │ │ │ └── Semaphore │ │ │ │ │ │ ├── Job.java │ │ │ │ │ │ ├── PrintQueue.java │ │ │ │ │ │ └── Test.java │ │ │ │ └── concurrentCollection │ │ │ │ │ ├── ConcurrentHashMap │ │ │ │ │ └── ConcurrentHashMapTest.java │ │ │ │ │ ├── CopyOnWriteArrayList │ │ │ │ │ └── CopyOnWriteArrayListTest.java │ │ │ │ │ └── CopyOnWriteArraySet │ │ │ │ │ └── CopyOnWriteArraySetTest.java │ │ │ ├── basic │ │ │ │ ├── InterruptedThread.java │ │ │ │ ├── JoinThread.java │ │ │ │ ├── MultiThread.java │ │ │ │ ├── ShutDownThread.java │ │ │ │ ├── ThreadState.java │ │ │ │ ├── WaitAndNotify.java │ │ │ │ └── synchronize │ │ │ │ │ ├── Account.java │ │ │ │ │ ├── Bank.java │ │ │ │ │ └── Company.java │ │ │ ├── model │ │ │ │ ├── GuardedSuspension │ │ │ │ │ ├── ClientThread.java │ │ │ │ │ ├── Request.java │ │ │ │ │ ├── RequestQueue.java │ │ │ │ │ ├── ServerThread.java │ │ │ │ │ └── Test.java │ │ │ │ └── MasterWorker │ │ │ │ │ ├── Master.java │ │ │ │ │ ├── PlusWorker.java │ │ │ │ │ ├── Test.java │ │ │ │ │ └── Worker.java │ │ │ └── threadPool │ │ │ │ └── custom │ │ │ │ ├── PThread.java │ │ │ │ ├── Test.java │ │ │ │ └── ThreadPool.java │ │ ├── junit │ │ │ └── _1 │ │ │ │ └── Calculator.java │ │ └── proxy │ │ │ ├── _1 │ │ │ ├── Client.java │ │ │ ├── ProxySubject.java │ │ │ ├── RealSubject.java │ │ │ └── Subject.java │ │ │ └── _2 │ │ │ ├── Client.java │ │ │ ├── DynamicSubject.java │ │ │ ├── RealSubject.java │ │ │ └── Subject.java │ │ └── redis │ │ ├── JRedisPoolUtils.java │ │ ├── JRedisTest.java │ │ ├── RedisInvokeTest.java │ │ └── Test.java └── resources │ └── rebel.xml └── test └── Test.java /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | target/ 3 | 4 | .idea 5 | *.iml -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | JavaCore 5 | JavaCore 6 | 0.0.1-SNAPSHOT 7 | 8 | 9 | 10 | junit 11 | junit 12 | 4.12 13 | 14 | 15 | 16 | redis.clients 17 | jedis 18 | 2.1.0 19 | 20 | 21 | 22 | commons-pool 23 | commons-pool 24 | 1.6 25 | 26 | 27 | 28 | io.netty 29 | netty-all 30 | 5.0.0.Alpha2 31 | 32 | 33 | 34 | 35 | src 36 | 37 | 38 | maven-compiler-plugin 39 | 3.1 40 | 41 | 1.7 42 | 1.7 43 | 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /src/main/java/com/JVM/heap/HeapGCTest.java: -------------------------------------------------------------------------------- 1 | package com.ufclub.ljs.autoInvest.model.AutoInvestSettingcom.JVM.heap; 2 | 3 | /** 4 | * Java GC测试 5 | * @author chenssy 6 | * @date 2016/11/19 7 | * @since v1.0.0 8 | */ 9 | public class HeapGCTest { 10 | //VM参数:-Xms=40 -Xmx40m -Xmn20m 11 | public static void main(String[] args){ 12 | byte[] b1 = new byte[1024 * 1024 / 2]; 13 | byte[] b2 = new byte[2014 * 1024 * 8]; 14 | 15 | b2 = null; 16 | b2 = new byte[2014 * 1024 * 8]; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/JVM/perm/PermGengc.java: -------------------------------------------------------------------------------- 1 | package com.ufclub.ljs.autoInvest.model.AutoInvestSettingcom.JVM.perm; 2 | 3 | /** 4 | * 常量池GC策略:只要常量池中的常量没有被任何地方引用,就可以被回收 5 | * @author chenssy 6 | * @date 2016/11/19 7 | * @since v1.0.0 8 | */ 9 | public class PermGengc { 10 | 11 | public static void main(String[] args){ 12 | for(int i = 0 ; i < Integer.MAX_VALUE ; i++){ 13 | String t = String.valueOf(i).intern(); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/JVM/stack/StackGCTest.java: -------------------------------------------------------------------------------- 1 | package com.ufclub.ljs.autoInvest.model.AutoInvestSettingcom.JVM.stack; 2 | 3 | /** 4 | * @author chenssy 5 | * @date 2016/11/19 6 | * @since v1.0.0 7 | */ 8 | public class StackGCTest { 9 | 10 | //如果一个局部变量被保存在局部变量表中,那么GC就能引用到这个局部变量所指向的内存空间 11 | //从而在GC时,可能无法回收这部分空间 12 | public static void test1(){ 13 | { 14 | byte[] bytes = new byte[6 * 1024 * 1024]; 15 | } 16 | System.gc(); 17 | System.out.println("first explict gc over"); 18 | } 19 | 20 | //手工释放该空间,将变量设置为null 21 | public static void test2(){ 22 | { 23 | byte[] bytes = new byte[6 * 1024 * 1024]; 24 | bytes = null; 25 | } 26 | System.gc(); 27 | System.out.println("first explict gc over"); 28 | } 29 | 30 | //或者重新声明一个新的局部变量,从而复用该变量的字,使其所占有的空间可以被GC回收 31 | public static void test3(){ 32 | { 33 | byte[] bytes = new byte[6 * 1024 * 1024]; 34 | } 35 | int a = 0; 36 | System.gc(); 37 | System.out.println("first explict gc over"); 38 | } 39 | 40 | 41 | public static void main(String[] args){ 42 | test1(); 43 | // test2(); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/JVM/stack/TestStack.java: -------------------------------------------------------------------------------- 1 | package com.JVM.stack; 2 | 3 | import org.junit.Test; 4 | 5 | /** 6 | * 测试当前栈的深度 7 | * 8 | * @author chenssy 9 | * @date 2016-11-15 10 | * @since v1.0.0 11 | */ 12 | public class TestStack { 13 | private int count = 0; 14 | 15 | public void recursion(){ 16 | count++; 17 | recursion(); 18 | } 19 | 20 | @Test 21 | public void testStack(){ 22 | try { 23 | recursion(); 24 | } catch (Throwable e) { 25 | System.out.println("Deep of stack is " + count); 26 | e.printStackTrace(); 27 | } 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/JVM/stack/WordReuseTest.java: -------------------------------------------------------------------------------- 1 | package com.JVM.stack; 2 | 3 | /** 4 | * 局部变量对GC的影响; 5 | * 6 | * 7 | * @author chenssy 8 | * @date 2016-11-17 9 | * @since v1.0.0 10 | */ 11 | public class WordReuseTest { 12 | public static void test(){ 13 | { 14 | byte[] b = new byte[6 * 1024 * 1024]; 15 | } 16 | System.gc(); 17 | System.out.println("first explict gc over"); 18 | } 19 | 20 | public static void main(String[] args){ 21 | test(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/NIO/core/BufferTest.java: -------------------------------------------------------------------------------- 1 | package com.NIO.core; 2 | 3 | import java.io.RandomAccessFile; 4 | import java.nio.ByteBuffer; 5 | import java.nio.channels.FileChannel; 6 | 7 | /** 8 | * Buffer测试
9 | * buffer使用步骤: 10 | * 1、写入数据到Buffer 11 | * 2、调用flip()方法 12 | * 3、从Buffer中读取数据 13 | * 4、调用clear()方法或者compact()方法 14 | * 15 | * @author chenming 16 | * @date 2016-11-21 17 | * @since v1.0.0 18 | */ 19 | public class BufferTest { 20 | public static void main(String[] args) throws Exception { 21 | RandomAccessFile file = new RandomAccessFile("E:/workspace/channelTest.txt","rw"); 22 | 23 | FileChannel fileChannel = file.getChannel(); 24 | 25 | //对buffer对象进行分配 26 | ByteBuffer buf = ByteBuffer.allocate(24); 27 | 28 | int bytesRead = fileChannel.read(buf); 29 | while (bytesRead != -1){ 30 | buf.flip(); //切换到读模式 31 | while (buf.hasRemaining()){ 32 | System.out.println((char)buf.get()); 33 | } 34 | 35 | buf.clear(); //清空缓存 36 | bytesRead = fileChannel.read(buf); 37 | } 38 | 39 | file.close(); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/NIO/core/ChannelTest.java: -------------------------------------------------------------------------------- 1 | package com.NIO.core; 2 | 3 | import java.io.RandomAccessFile; 4 | import java.nio.ByteBuffer; 5 | import java.nio.channels.FileChannel; 6 | 7 | public class ChannelTest { 8 | public static void main(String[] args) throws Exception { 9 | RandomAccessFile file = new RandomAccessFile("E:/workspace/channelTest.txt","rw"); 10 | 11 | FileChannel fileChannel = file.getChannel(); 12 | 13 | ByteBuffer buf = ByteBuffer.allocate(8); 14 | 15 | int bytesRead = fileChannel.read(buf); 16 | while (bytesRead != -1){ 17 | System.out.println("Read " + bytesRead); 18 | buf.flip(); 19 | while (buf.hasRemaining()){ 20 | System.out.println((char)buf.get()); 21 | } 22 | 23 | buf.clear(); 24 | bytesRead = fileChannel.read(buf); 25 | } 26 | 27 | file.close(); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/NIO/netty/Http/fileServer/HttpFileServer.java: -------------------------------------------------------------------------------- 1 | package com.NIO.netty.Http.fileServer; 2 | 3 | import io.netty.bootstrap.ServerBootstrap; 4 | import io.netty.channel.ChannelFuture; 5 | import io.netty.channel.ChannelInitializer; 6 | import io.netty.channel.EventLoopGroup; 7 | import io.netty.channel.nio.NioEventLoopGroup; 8 | import io.netty.channel.socket.SocketChannel; 9 | import io.netty.channel.socket.nio.NioServerSocketChannel; 10 | import io.netty.handler.codec.http.HttpObjectAggregator; 11 | import io.netty.handler.codec.http.HttpRequestDecoder; 12 | import io.netty.handler.codec.http.HttpResponseEncoder; 13 | import io.netty.handler.stream.ChunkedWriteHandler; 14 | 15 | public class HttpFileServer { 16 | private static final String DEFAULT_URL = "/src/main/java/come/NIO/netty"; 17 | 18 | public void run(int port, final String url) throws Exception { 19 | EventLoopGroup bossGroup = new NioEventLoopGroup(); 20 | EventLoopGroup workerGroup = new NioEventLoopGroup(); 21 | 22 | try{ 23 | ServerBootstrap sb = new ServerBootstrap(); 24 | sb.group(bossGroup,workerGroup) 25 | .channel(NioServerSocketChannel.class) 26 | .childHandler(new ChannelInitializer() { 27 | @Override 28 | protected void initChannel(SocketChannel socketChannel) throws Exception { 29 | socketChannel.pipeline().addLast("http-decoder",new HttpRequestDecoder()); 30 | socketChannel.pipeline().addLast("http-aggregator",new HttpObjectAggregator(65536)); 31 | socketChannel.pipeline().addLast("http-encoder",new HttpResponseEncoder()); 32 | socketChannel.pipeline().addLast("http-chunked",new ChunkedWriteHandler()); 33 | socketChannel.pipeline().addLast("fileServerHandler",new HttpFileServerHandler(url)); 34 | } 35 | }); 36 | 37 | ChannelFuture future = sb.bind("127.0.0.1",port); 38 | System.out.println("HTTP 文件目录服务器启动,网址是:http://127.0.0.1"); 39 | 40 | future.channel().closeFuture().sync(); 41 | }finally { 42 | bossGroup.shutdownGracefully(); 43 | workerGroup.shutdownGracefully(); 44 | } 45 | } 46 | 47 | public static void main(String[] args) throws Exception { 48 | new HttpFileServer().run(8999,"127.0.0.1"); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/NIO/netty/Http/fileServer/HttpFileServerHandler.java: -------------------------------------------------------------------------------- 1 | package com.NIO.netty.Http.fileServer; 2 | 3 | import io.netty.channel.ChannelHandlerContext; 4 | import io.netty.channel.SimpleChannelInboundHandler; 5 | import io.netty.handler.codec.http.FullHttpRequest; 6 | 7 | public class HttpFileServerHandler extends SimpleChannelInboundHandler{ 8 | public HttpFileServerHandler(String url) { 9 | 10 | } 11 | 12 | @Override 13 | protected void messageReceived(ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest) throws Exception { 14 | 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/NIO/netty/base/TimeClient.java: -------------------------------------------------------------------------------- 1 | package com.NIO.netty.base; 2 | 3 | import io.netty.bootstrap.Bootstrap; 4 | import io.netty.channel.*; 5 | import io.netty.channel.nio.NioEventLoopGroup; 6 | import io.netty.channel.socket.SocketChannel; 7 | import io.netty.channel.socket.nio.NioSocketChannel; 8 | 9 | public class TimeClient { 10 | 11 | public void connect(int port, String host) { 12 | // 配置客户端线程组 13 | EventLoopGroup group = new NioEventLoopGroup(); 14 | 15 | Bootstrap b = new Bootstrap(); 16 | 17 | try { 18 | b.group(group).channel(NioSocketChannel.class) 19 | .option(ChannelOption.TCP_NODELAY, true) 20 | .handler(new ChannelInitializer() { 21 | @Override 22 | protected void initChannel(SocketChannel socketChannel) throws Exception { 23 | socketChannel.pipeline().addLast(new TimeClientHandler()); 24 | } 25 | }); 26 | 27 | // 发起异步连接操作 28 | ChannelFuture future = b.connect(host, port); 29 | 30 | // 等待客户端链路关闭 31 | 32 | 33 | future.channel().closeFuture().sync(); 34 | } catch (InterruptedException e) { 35 | 36 | } finally { 37 | group.shutdownGracefully(); 38 | } 39 | } 40 | 41 | public static void main(String[] args) { 42 | new TimeClient().connect(8899,"127.0.0.1"); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/NIO/netty/base/TimeClientHandler.java: -------------------------------------------------------------------------------- 1 | package com.NIO.netty.base; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import io.netty.buffer.Unpooled; 5 | import io.netty.channel.ChannelHandlerAdapter; 6 | import io.netty.channel.ChannelHandlerContext; 7 | 8 | public class TimeClientHandler extends ChannelHandlerAdapter{ 9 | 10 | private final ByteBuf firstMessage; 11 | 12 | public TimeClientHandler(){ 13 | byte[] req = "QUERY TIME ORDER".getBytes(); 14 | firstMessage = Unpooled.buffer(req.length); 15 | 16 | firstMessage.writeBytes(req); 17 | } 18 | 19 | 20 | 21 | @Override 22 | public void channelActive(ChannelHandlerContext ctx) throws Exception { 23 | ctx.writeAndFlush(firstMessage); 24 | } 25 | 26 | @Override 27 | public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { 28 | ByteBuf buf = (ByteBuf) msg; 29 | 30 | byte[] req = new byte[buf.readableBytes()]; 31 | buf.readBytes(req); 32 | 33 | String body = new String(req,"UTF-8"); 34 | 35 | System.out.println("Now is :" + body); 36 | } 37 | 38 | @Override 39 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { 40 | 41 | System.out.println("cause by :" + cause.getMessage()); 42 | 43 | ctx.close(); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/NIO/netty/base/TimeServer.java: -------------------------------------------------------------------------------- 1 | package com.NIO.netty.base; 2 | 3 | import io.netty.bootstrap.ServerBootstrap; 4 | import io.netty.channel.ChannelFuture; 5 | import io.netty.channel.ChannelInitializer; 6 | import io.netty.channel.ChannelOption; 7 | import io.netty.channel.EventLoopGroup; 8 | import io.netty.channel.nio.NioEventLoopGroup; 9 | import io.netty.channel.socket.SocketChannel; 10 | import io.netty.channel.socket.nio.NioServerSocketChannel; 11 | 12 | public class TimeServer { 13 | 14 | public void bind(int port){ 15 | // 配置服务端的NIO线程组 16 | EventLoopGroup bossGroup = new NioEventLoopGroup(); // 用于服务端接受客户端的连接 17 | EventLoopGroup workerGroup = new NioEventLoopGroup(); // 用于进行SocketChannel的网络读写 18 | 19 | try { 20 | // ServerBootstrap 用于启动NIO服务端的辅助启动类,目的是降低服务端的开发复杂度 21 | ServerBootstrap b = new ServerBootstrap(); 22 | b.group(bossGroup, workerGroup) 23 | .channel(NioServerSocketChannel.class) 24 | .option(ChannelOption.SO_BACKLOG, 1024) 25 | .childHandler(new ChildChannelHanlder()); 26 | 27 | // 绑定端口,同步等待成功 28 | ChannelFuture future = b.bind(port).sync(); 29 | // 等待服务端监听端口关闭 30 | future.channel().closeFuture().sync(); 31 | 32 | } catch (InterruptedException e) { 33 | e.printStackTrace(); 34 | } finally { 35 | // 优雅地关闭 36 | bossGroup.shutdownGracefully(); 37 | workerGroup.shutdownGracefully(); 38 | } 39 | } 40 | 41 | private class ChildChannelHanlder extends ChannelInitializer{ 42 | 43 | @Override 44 | protected void initChannel(SocketChannel socketChannel) throws Exception { 45 | socketChannel.pipeline().addLast(new TimerServerHandler()); 46 | } 47 | } 48 | 49 | public static void main(String[] args){ 50 | new TimeServer().bind(8899); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/com/NIO/netty/base/TimerServerHandler.java: -------------------------------------------------------------------------------- 1 | package com.NIO.netty.base; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import io.netty.buffer.Unpooled; 5 | import io.netty.channel.ChannelHandlerAdapter; 6 | import io.netty.channel.ChannelHandlerContext; 7 | 8 | import java.util.Date; 9 | 10 | 11 | public class TimerServerHandler extends ChannelHandlerAdapter{ 12 | 13 | @Override 14 | public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { 15 | ByteBuf buf = (ByteBuf) msg; 16 | 17 | byte[] req = new byte[buf.readableBytes()]; 18 | buf.readBytes(req); 19 | 20 | String body = new String(req,"UTF-8"); 21 | System.out.println("The time server receive order:" + body); 22 | 23 | String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new Date(System.currentTimeMillis()).toString() : "BAD ORDER"; 24 | 25 | ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes()); 26 | 27 | ctx.write(resp); 28 | } 29 | 30 | @Override 31 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { 32 | ctx.close(); 33 | } 34 | 35 | @Override 36 | public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { 37 | ctx.flush(); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/NIO/netty/frameDecoder/DelimiterBasedFrameDecoder/EchoClient.java: -------------------------------------------------------------------------------- 1 | package com.NIO.netty.frameDecoder.DelimiterBasedFrameDecoder; 2 | 3 | import io.netty.bootstrap.Bootstrap; 4 | import io.netty.buffer.ByteBuf; 5 | import io.netty.buffer.Unpooled; 6 | import io.netty.channel.ChannelFuture; 7 | import io.netty.channel.ChannelInitializer; 8 | import io.netty.channel.ChannelOption; 9 | import io.netty.channel.EventLoopGroup; 10 | import io.netty.channel.nio.NioEventLoopGroup; 11 | import io.netty.channel.socket.SocketChannel; 12 | import io.netty.channel.socket.nio.NioSocketChannel; 13 | import io.netty.handler.codec.DelimiterBasedFrameDecoder; 14 | import io.netty.handler.codec.string.StringDecoder; 15 | 16 | public class EchoClient { 17 | public void connect(int port,String host) throws Exception { 18 | EventLoopGroup group = new NioEventLoopGroup(); 19 | 20 | try { 21 | Bootstrap sb = new Bootstrap(); 22 | sb.group(group).channel(NioSocketChannel.class) 23 | .option(ChannelOption.TCP_NODELAY, true) 24 | .handler(new ChannelInitializer() { 25 | @Override 26 | protected void initChannel(SocketChannel socketChannel) throws Exception { 27 | ByteBuf delimiter = Unpooled.copiedBuffer("$_".getBytes()); 28 | 29 | socketChannel.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, delimiter)); 30 | 31 | socketChannel.pipeline().addLast(new StringDecoder()); 32 | 33 | socketChannel.pipeline().addLast(new EchoClientHandler()); 34 | } 35 | }); 36 | 37 | ChannelFuture f = sb.connect(host,port).sync(); 38 | 39 | f.channel().closeFuture().sync(); 40 | } finally { 41 | group.shutdownGracefully(); 42 | } 43 | } 44 | 45 | public static void main(String[] args) throws Exception { 46 | new EchoClient().connect(8999,"127.0.0.1"); 47 | } 48 | 49 | 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/NIO/netty/frameDecoder/DelimiterBasedFrameDecoder/EchoClientHandler.java: -------------------------------------------------------------------------------- 1 | package com.NIO.netty.frameDecoder.DelimiterBasedFrameDecoder; 2 | 3 | import io.netty.buffer.Unpooled; 4 | import io.netty.channel.ChannelHandlerAdapter; 5 | import io.netty.channel.ChannelHandlerContext; 6 | 7 | public class EchoClientHandler extends ChannelHandlerAdapter{ 8 | private int counter; 9 | 10 | // 末尾增加$_ 11 | static final String ECHO_REQ = "Hi,chenssy,welcome to netty.$_"; 12 | 13 | @Override 14 | public void channelActive(ChannelHandlerContext ctx) throws Exception { 15 | for(int i = 0 ; i < 10 ; i++){ 16 | ctx.writeAndFlush(Unpooled.copiedBuffer(ECHO_REQ.getBytes())); 17 | } 18 | } 19 | 20 | @Override 21 | public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { 22 | System.out.println("This is " + (++counter) + " times receive server:[" + msg + "]"); 23 | } 24 | 25 | @Override 26 | public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { 27 | ctx.flush(); 28 | } 29 | 30 | @Override 31 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { 32 | cause.printStackTrace(); 33 | ctx.close(); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/NIO/netty/frameDecoder/DelimiterBasedFrameDecoder/EchoServer.java: -------------------------------------------------------------------------------- 1 | package com.NIO.netty.frameDecoder.DelimiterBasedFrameDecoder; 2 | 3 | import io.netty.bootstrap.ServerBootstrap; 4 | import io.netty.buffer.ByteBuf; 5 | import io.netty.buffer.Unpooled; 6 | import io.netty.channel.*; 7 | import io.netty.channel.nio.NioEventLoopGroup; 8 | import io.netty.channel.socket.SocketChannel; 9 | import io.netty.channel.socket.nio.NioServerSocketChannel; 10 | import io.netty.handler.codec.DelimiterBasedFrameDecoder; 11 | import io.netty.handler.codec.string.StringDecoder; 12 | 13 | /** 14 | * DelimiterBasedFrameDecoder 服务端 15 | * 16 | * @author chenssy 17 | * @date 2017-05-08 18 | * @since v1.0.0 19 | */ 20 | public class EchoServer { 21 | 22 | public void bind(int port) throws Exception { 23 | // 配置线程组 24 | EventLoopGroup boosGroup = new NioEventLoopGroup(); 25 | EventLoopGroup workerGroup = new NioEventLoopGroup(); 26 | 27 | try { 28 | ServerBootstrap sb = new ServerBootstrap(); 29 | sb.group(boosGroup, workerGroup) 30 | .channel(NioServerSocketChannel.class) 31 | .option(ChannelOption.SO_BACKLOG, 100) 32 | .childHandler(new ChannelInitializer() { 33 | @Override 34 | protected void initChannel(SocketChannel channel) throws Exception { 35 | ByteBuf delimiter = Unpooled.copiedBuffer("$_".getBytes()); 36 | channel.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, delimiter)); 37 | 38 | channel.pipeline().addLast(new StringDecoder()); 39 | channel.pipeline().addLast(new EchoServerHandler()); 40 | } 41 | }); 42 | 43 | //绑定端口 44 | ChannelFuture f = sb.bind(port).sync(); 45 | 46 | //等待服务端监听端口关闭 47 | f.channel().closeFuture().sync(); 48 | } finally { 49 | boosGroup.shutdownGracefully(); 50 | workerGroup.shutdownGracefully(); 51 | } 52 | } 53 | 54 | public static void main(String[] args) throws Exception { 55 | new EchoServer().bind(8999); 56 | } 57 | 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/com/NIO/netty/frameDecoder/DelimiterBasedFrameDecoder/EchoServerHandler.java: -------------------------------------------------------------------------------- 1 | package com.NIO.netty.frameDecoder.DelimiterBasedFrameDecoder; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import io.netty.buffer.Unpooled; 5 | import io.netty.channel.ChannelHandlerAdapter; 6 | import io.netty.channel.ChannelHandlerContext; 7 | 8 | public class EchoServerHandler extends ChannelHandlerAdapter{ 9 | 10 | private int counter = 0; 11 | 12 | @Override 13 | public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { 14 | String body = (String) msg; 15 | 16 | System.out.println("This is " + (++counter) + " times reveive client:[" + body + "]"); 17 | 18 | if(counter % 3 == 0){ 19 | body += "$_"; 20 | } 21 | 22 | ByteBuf buf = Unpooled.copiedBuffer(body.getBytes()); 23 | 24 | ctx.writeAndFlush(buf); 25 | } 26 | 27 | @Override 28 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { 29 | cause.printStackTrace(); 30 | ctx.close(); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/NIO/netty/frameDecoder/FixedLengthFrameDecoder/EchoServer.java: -------------------------------------------------------------------------------- 1 | package com.NIO.netty.frameDecoder.FixedLengthFrameDecoder; 2 | 3 | import io.netty.bootstrap.ServerBootstrap; 4 | import io.netty.buffer.ByteBuf; 5 | import io.netty.buffer.Unpooled; 6 | import io.netty.channel.ChannelFuture; 7 | import io.netty.channel.ChannelInitializer; 8 | import io.netty.channel.ChannelOption; 9 | import io.netty.channel.EventLoopGroup; 10 | import io.netty.channel.nio.NioEventLoopGroup; 11 | import io.netty.channel.socket.SocketChannel; 12 | import io.netty.channel.socket.nio.NioServerSocketChannel; 13 | import io.netty.handler.codec.DelimiterBasedFrameDecoder; 14 | import io.netty.handler.codec.FixedLengthFrameDecoder; 15 | import io.netty.handler.codec.string.StringDecoder; 16 | 17 | /** 18 | * DelimiterBasedFrameDecoder 服务端 19 | * 20 | * @author chenssy 21 | * @date 2017-05-08 22 | * @since v1.0.0 23 | */ 24 | public class EchoServer { 25 | 26 | public void bind(int port) throws Exception { 27 | // 配置线程组 28 | EventLoopGroup boosGroup = new NioEventLoopGroup(); 29 | EventLoopGroup workerGroup = new NioEventLoopGroup(); 30 | 31 | try { 32 | ServerBootstrap sb = new ServerBootstrap(); 33 | sb.group(boosGroup, workerGroup) 34 | .channel(NioServerSocketChannel.class) 35 | .option(ChannelOption.SO_BACKLOG, 100) 36 | .childHandler(new ChannelInitializer() { 37 | @Override 38 | protected void initChannel(SocketChannel channel) throws Exception { 39 | channel.pipeline().addLast(new FixedLengthFrameDecoder(20)); 40 | 41 | channel.pipeline().addLast(new StringDecoder()); 42 | channel.pipeline().addLast(new EchoServerHandler()); 43 | } 44 | }); 45 | 46 | //绑定端口 47 | ChannelFuture f = sb.bind(port).sync(); 48 | 49 | //等待服务端监听端口关闭 50 | f.channel().closeFuture().sync(); 51 | } finally { 52 | boosGroup.shutdownGracefully(); 53 | workerGroup.shutdownGracefully(); 54 | } 55 | } 56 | 57 | public static void main(String[] args) throws Exception { 58 | new EchoServer().bind(8999); 59 | } 60 | 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/com/NIO/netty/frameDecoder/FixedLengthFrameDecoder/EchoServerHandler.java: -------------------------------------------------------------------------------- 1 | package com.NIO.netty.frameDecoder.FixedLengthFrameDecoder; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import io.netty.buffer.Unpooled; 5 | import io.netty.channel.ChannelHandlerAdapter; 6 | import io.netty.channel.ChannelHandlerContext; 7 | 8 | public class EchoServerHandler extends ChannelHandlerAdapter{ 9 | 10 | @Override 11 | public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { 12 | String body = (String) msg; 13 | 14 | System.out.println("Receive client : [" + body + "]"); 15 | 16 | ByteBuf buf = Unpooled.copiedBuffer(body.getBytes()); 17 | 18 | ctx.writeAndFlush(buf); 19 | } 20 | 21 | @Override 22 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { 23 | cause.printStackTrace(); 24 | ctx.close(); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/NIO/netty/tcpIP/NotStickers/TimeClient.java: -------------------------------------------------------------------------------- 1 | package com.NIO.netty.tcpIP.NotStickers; 2 | 3 | import io.netty.bootstrap.Bootstrap; 4 | import io.netty.channel.ChannelFuture; 5 | import io.netty.channel.ChannelInitializer; 6 | import io.netty.channel.ChannelOption; 7 | import io.netty.channel.EventLoopGroup; 8 | import io.netty.channel.nio.NioEventLoopGroup; 9 | import io.netty.channel.socket.SocketChannel; 10 | import io.netty.channel.socket.nio.NioSocketChannel; 11 | 12 | public class TimeClient { 13 | 14 | public void connect(int port, String host) { 15 | // 配置客户端线程组 16 | EventLoopGroup group = new NioEventLoopGroup(); 17 | 18 | Bootstrap b = new Bootstrap(); 19 | 20 | try { 21 | b.group(group).channel(NioSocketChannel.class) 22 | .option(ChannelOption.TCP_NODELAY, true) 23 | .handler(new ChannelInitializer() { 24 | @Override 25 | protected void initChannel(SocketChannel socketChannel) throws Exception { 26 | socketChannel.pipeline().addLast(new TimeClientHandler()); 27 | } 28 | }); 29 | 30 | // 发起异步连接操作 31 | ChannelFuture future = b.connect(host, port); 32 | 33 | // 等待客户端链路关闭 34 | 35 | future.channel().closeFuture().sync(); 36 | } catch (InterruptedException e) { 37 | 38 | } finally { 39 | group.shutdownGracefully(); 40 | } 41 | } 42 | 43 | public static void main(String[] args) { 44 | new TimeClient().connect(8899,"127.0.0.1"); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/NIO/netty/tcpIP/NotStickers/TimeClientHandler.java: -------------------------------------------------------------------------------- 1 | package com.NIO.netty.tcpIP.NotStickers; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import io.netty.buffer.Unpooled; 5 | import io.netty.channel.ChannelHandlerAdapter; 6 | import io.netty.channel.ChannelHandlerContext; 7 | 8 | public class TimeClientHandler extends ChannelHandlerAdapter{ 9 | 10 | private int counter; 11 | 12 | private byte[] req; 13 | 14 | 15 | public TimeClientHandler(){ 16 | req = ("QUERY TIME ORDER" + System.getProperty("line.separator")).getBytes(); 17 | } 18 | 19 | 20 | 21 | @Override 22 | public void channelActive(ChannelHandlerContext ctx) throws Exception { 23 | ByteBuf message = null; 24 | 25 | for (int i = 0 ; i < 100 ; i++){ 26 | message = Unpooled.buffer(req.length); 27 | message.writeBytes(req); 28 | 29 | ctx.writeAndFlush(message); 30 | } 31 | } 32 | 33 | @Override 34 | public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { 35 | ByteBuf buf = (ByteBuf) msg; 36 | 37 | byte[] req = new byte[buf.readableBytes()]; 38 | buf.readBytes(req); 39 | 40 | String body = new String(req,"UTF-8"); 41 | 42 | System.out.println("Now is :" + body + "; the conters is :" + (++counter)); 43 | } 44 | 45 | @Override 46 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { 47 | 48 | System.out.println("cause by :" + cause.getMessage()); 49 | 50 | ctx.close(); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/com/NIO/netty/tcpIP/NotStickers/TimeServer.java: -------------------------------------------------------------------------------- 1 | package com.NIO.netty.tcpIP.NotStickers; 2 | 3 | import io.netty.bootstrap.ServerBootstrap; 4 | import io.netty.channel.ChannelFuture; 5 | import io.netty.channel.ChannelInitializer; 6 | import io.netty.channel.ChannelOption; 7 | import io.netty.channel.EventLoopGroup; 8 | import io.netty.channel.nio.NioEventLoopGroup; 9 | import io.netty.channel.socket.SocketChannel; 10 | import io.netty.channel.socket.nio.NioServerSocketChannel; 11 | 12 | public class TimeServer { 13 | 14 | public void bind(int port){ 15 | // 配置服务端的NIO线程组 16 | EventLoopGroup bossGroup = new NioEventLoopGroup(); // 用于服务端接受客户端的连接 17 | EventLoopGroup workerGroup = new NioEventLoopGroup(); // 用于进行SocketChannel的网络读写 18 | 19 | try { 20 | // ServerBootstrap 用于启动NIO服务端的辅助启动类,目的是降低服务端的开发复杂度 21 | ServerBootstrap b = new ServerBootstrap(); 22 | b.group(bossGroup, workerGroup) 23 | .channel(NioServerSocketChannel.class) 24 | .option(ChannelOption.SO_BACKLOG, 1024) 25 | .childHandler(new ChildChannelHanlder()); 26 | 27 | // 绑定端口,同步等待成功 28 | ChannelFuture future = b.bind(port).sync(); 29 | // 等待服务端监听端口关闭 30 | future.channel().closeFuture().sync(); 31 | 32 | } catch (InterruptedException e) { 33 | e.printStackTrace(); 34 | } finally { 35 | // 优雅地关闭 36 | bossGroup.shutdownGracefully(); 37 | workerGroup.shutdownGracefully(); 38 | } 39 | } 40 | 41 | private class ChildChannelHanlder extends ChannelInitializer{ 42 | 43 | @Override 44 | protected void initChannel(SocketChannel socketChannel) throws Exception { 45 | socketChannel.pipeline().addLast(new TimerServerHandler()); 46 | } 47 | } 48 | 49 | public static void main(String[] args){ 50 | new TimeServer().bind(8899); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/com/NIO/netty/tcpIP/NotStickers/TimerServerHandler.java: -------------------------------------------------------------------------------- 1 | package com.NIO.netty.tcpIP.NotStickers; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import io.netty.buffer.Unpooled; 5 | import io.netty.channel.ChannelHandlerAdapter; 6 | import io.netty.channel.ChannelHandlerContext; 7 | 8 | import java.util.Date; 9 | 10 | /** 11 | * 未考虑粘包拆包 12 | * 13 | * @author chenssy 14 | * @date 2017-05-05 15 | * @since v1.0.0 16 | */ 17 | public class TimerServerHandler extends ChannelHandlerAdapter{ 18 | 19 | private int counter; 20 | 21 | @Override 22 | public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { 23 | ByteBuf buf = (ByteBuf) msg; 24 | 25 | byte[] req = new byte[buf.readableBytes()]; 26 | buf.readBytes(req); 27 | 28 | String body = new String(req,"UTF-8").substring(0,req.length - System.getProperty("line.separator").length()); 29 | 30 | System.out.println("The time server receive order:" + body + "; the counter is " + (++counter)); 31 | 32 | String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new Date(System.currentTimeMillis()).toString() : "BAD ORDER"; 33 | 34 | currentTime = currentTime + System.getProperty("line.separator"); 35 | 36 | ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes()); 37 | 38 | ctx.writeAndFlush(resp); 39 | } 40 | 41 | @Override 42 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { 43 | ctx.close(); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/NIO/netty/tcpIP/stickers/TimeClient.java: -------------------------------------------------------------------------------- 1 | package com.NIO.netty.tcpIP.stickers; 2 | 3 | import io.netty.bootstrap.Bootstrap; 4 | import io.netty.channel.ChannelFuture; 5 | import io.netty.channel.ChannelInitializer; 6 | import io.netty.channel.ChannelOption; 7 | import io.netty.channel.EventLoopGroup; 8 | import io.netty.channel.nio.NioEventLoopGroup; 9 | import io.netty.channel.socket.SocketChannel; 10 | import io.netty.channel.socket.nio.NioSocketChannel; 11 | import io.netty.handler.codec.LineBasedFrameDecoder; 12 | import io.netty.handler.codec.string.StringDecoder; 13 | 14 | public class TimeClient { 15 | 16 | public void connect(int port, String host) { 17 | // 配置客户端线程组 18 | EventLoopGroup group = new NioEventLoopGroup(); 19 | 20 | Bootstrap b = new Bootstrap(); 21 | 22 | try { 23 | b.group(group).channel(NioSocketChannel.class) 24 | .option(ChannelOption.TCP_NODELAY, true) 25 | .handler(new ChannelInitializer() { 26 | @Override 27 | protected void initChannel(SocketChannel socketChannel) throws Exception { 28 | socketChannel.pipeline().addLast(new LineBasedFrameDecoder(1024)); 29 | socketChannel.pipeline().addLast(new StringDecoder()); 30 | socketChannel.pipeline().addLast(new TimeClientHandler()); 31 | } 32 | }); 33 | 34 | // 发起异步连接操作 35 | ChannelFuture future = b.connect(host, port); 36 | 37 | // 等待客户端链路关闭 38 | 39 | future.channel().closeFuture().sync(); 40 | } catch (InterruptedException e) { 41 | 42 | } finally { 43 | group.shutdownGracefully(); 44 | } 45 | } 46 | 47 | public static void main(String[] args) { 48 | new TimeClient().connect(8899,"127.0.0.1"); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/NIO/netty/tcpIP/stickers/TimeClientHandler.java: -------------------------------------------------------------------------------- 1 | package com.NIO.netty.tcpIP.stickers; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import io.netty.buffer.Unpooled; 5 | import io.netty.channel.ChannelHandlerAdapter; 6 | import io.netty.channel.ChannelHandlerContext; 7 | 8 | public class TimeClientHandler extends ChannelHandlerAdapter{ 9 | 10 | private int counter; 11 | 12 | private byte[] req; 13 | 14 | 15 | public TimeClientHandler(){ 16 | req = ("QUERY TIME ORDER" + System.getProperty("line.separator")).getBytes(); 17 | } 18 | 19 | 20 | 21 | @Override 22 | public void channelActive(ChannelHandlerContext ctx) throws Exception { 23 | ByteBuf message = null; 24 | 25 | for (int i = 0 ; i < 100 ; i++){ 26 | message = Unpooled.buffer(req.length); 27 | message.writeBytes(req); 28 | 29 | ctx.writeAndFlush(message); 30 | } 31 | } 32 | 33 | @Override 34 | public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { 35 | 36 | 37 | String body = (String) msg; 38 | 39 | System.out.println("Now is :" + body + "; the conters is :" + (++counter)); 40 | } 41 | 42 | @Override 43 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { 44 | 45 | System.out.println("cause by :" + cause.getMessage()); 46 | 47 | ctx.close(); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/NIO/netty/tcpIP/stickers/TimeServer.java: -------------------------------------------------------------------------------- 1 | package com.NIO.netty.tcpIP.stickers; 2 | 3 | import io.netty.bootstrap.ServerBootstrap; 4 | import io.netty.channel.ChannelFuture; 5 | import io.netty.channel.ChannelInitializer; 6 | import io.netty.channel.ChannelOption; 7 | import io.netty.channel.EventLoopGroup; 8 | import io.netty.channel.nio.NioEventLoopGroup; 9 | import io.netty.channel.socket.SocketChannel; 10 | import io.netty.channel.socket.nio.NioServerSocketChannel; 11 | import io.netty.handler.codec.LineBasedFrameDecoder; 12 | import io.netty.handler.codec.string.StringDecoder; 13 | 14 | 15 | public class TimeServer { 16 | 17 | public void bind(int port){ 18 | // 配置服务端的NIO线程组 19 | EventLoopGroup bossGroup = new NioEventLoopGroup(); // 用于服务端接受客户端的连接 20 | EventLoopGroup workerGroup = new NioEventLoopGroup(); // 用于进行SocketChannel的网络读写 21 | 22 | try { 23 | // ServerBootstrap 用于启动NIO服务端的辅助启动类,目的是降低服务端的开发复杂度 24 | ServerBootstrap b = new ServerBootstrap(); 25 | b.group(bossGroup, workerGroup) 26 | .channel(NioServerSocketChannel.class) 27 | .option(ChannelOption.SO_BACKLOG, 1024) 28 | .childHandler(new ChildChannelHanlder()); 29 | 30 | // 绑定端口,同步等待成功 31 | ChannelFuture future = b.bind(port).sync(); 32 | // 等待服务端监听端口关闭 33 | future.channel().closeFuture().sync(); 34 | 35 | } catch (InterruptedException e) { 36 | e.printStackTrace(); 37 | } finally { 38 | // 优雅地关闭 39 | bossGroup.shutdownGracefully(); 40 | workerGroup.shutdownGracefully(); 41 | } 42 | } 43 | 44 | private class ChildChannelHanlder extends ChannelInitializer{ 45 | 46 | @Override 47 | protected void initChannel(SocketChannel socketChannel) throws Exception { 48 | 49 | // 解码器 50 | socketChannel.pipeline().addLast(new LineBasedFrameDecoder(1024)); 51 | socketChannel.pipeline().addLast(new StringDecoder()); 52 | 53 | // 服务处理 54 | socketChannel.pipeline().addLast(new TimerServerHandler()); 55 | } 56 | } 57 | 58 | public static void main(String[] args){ 59 | new TimeServer().bind(8899); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/com/NIO/netty/tcpIP/stickers/TimerServerHandler.java: -------------------------------------------------------------------------------- 1 | package com.NIO.netty.tcpIP.stickers; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import io.netty.buffer.Unpooled; 5 | import io.netty.channel.ChannelHandlerAdapter; 6 | import io.netty.channel.ChannelHandlerContext; 7 | 8 | import java.util.Date; 9 | 10 | /** 11 | * 未考虑粘包拆包 12 | * 13 | * @author chenssy 14 | * @date 2017-05-05 15 | * @since v1.0.0 16 | */ 17 | public class TimerServerHandler extends ChannelHandlerAdapter{ 18 | 19 | private int counter; 20 | 21 | @Override 22 | public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { 23 | String body = (String) msg; 24 | 25 | System.out.println("The time server receive order:" + body + "; the counter is :" + (++counter)); 26 | 27 | String currentTime = " QUERY TIME ORDER".equalsIgnoreCase(body) ? new Date(System.currentTimeMillis()).toString() : "BAD ORDER"; 28 | 29 | currentTime = currentTime + System.getProperty("line.separator"); 30 | 31 | ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes()); 32 | 33 | ctx.writeAndFlush(resp); 34 | } 35 | 36 | @Override 37 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { 38 | ctx.close(); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/NIO/nio/_1/MultiplexerTimerServer.java: -------------------------------------------------------------------------------- 1 | package com.NIO.nio._1; 2 | 3 | import java.io.IOException; 4 | import java.net.InetSocketAddress; 5 | import java.nio.ByteBuffer; 6 | import java.nio.channels.SelectionKey; 7 | import java.nio.channels.Selector; 8 | import java.nio.channels.ServerSocketChannel; 9 | import java.nio.channels.SocketChannel; 10 | import java.util.Date; 11 | import java.util.Iterator; 12 | import java.util.Set; 13 | 14 | /** 15 | * 服务器端 16 | * 17 | * @author chenssy 18 | * @date 2017-04-20 19 | * @since v1.0.0 20 | */ 21 | public class MultiplexerTimerServer implements Runnable{ 22 | 23 | // 多路复用器 24 | private Selector selector; 25 | 26 | // 通道 27 | private ServerSocketChannel serverSocketChannel; 28 | 29 | private volatile boolean stop; 30 | 31 | MultiplexerTimerServer(int port){ 32 | try { 33 | // 打开通道channel,监听客户端连接 34 | selector = Selector.open(); 35 | 36 | serverSocketChannel = ServerSocketChannel.open(); 37 | //监听端口 38 | serverSocketChannel.socket().bind(new InetSocketAddress(port),1024); 39 | // 设置为非阻塞 40 | serverSocketChannel.configureBlocking(false); 41 | 42 | //将通道channel注册到多路复用器selector上面 43 | serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); 44 | 45 | System.out.println("The time server is start in port:" + port); 46 | } catch (IOException e) { 47 | e.printStackTrace(); 48 | } 49 | } 50 | 51 | public void stop(){ 52 | this.stop = true; 53 | } 54 | 55 | @Override 56 | public void run() { 57 | while (!stop){ 58 | try { 59 | selector.select(1000); 60 | 61 | Set selectionKeys = selector.selectedKeys(); 62 | Iterator it = selectionKeys.iterator(); 63 | 64 | SelectionKey key = null; 65 | 66 | while (it.hasNext()){ 67 | key = it.next(); 68 | 69 | it.remove(); 70 | 71 | try { 72 | handleInput(key); 73 | } catch (IOException e) { 74 | if(key != null){ 75 | key.cancel(); 76 | if(key.channel() != null){ 77 | key.channel().close(); 78 | } 79 | } 80 | } 81 | } 82 | } catch (IOException e) { 83 | e.printStackTrace(); 84 | } 85 | } 86 | 87 | // 多路复用器关闭后,所有注册在上面的Channel等资源都会自动去注册并关闭,所以不需要重复释放资源 88 | if(selector != null){ 89 | try { 90 | selector.close(); 91 | } catch (IOException e) { 92 | e.printStackTrace(); 93 | } 94 | } 95 | } 96 | 97 | /** 98 | * 处理链接请求 99 | * 100 | * @author chenssy 101 | * @date 2017-04-20 102 | * @since v1.0.0 103 | */ 104 | private void handleInput(SelectionKey key) throws IOException { 105 | if(key.isValid()){ 106 | // 处理新接入的请求 107 | if(key.isAcceptable()){ 108 | ServerSocketChannel ssc = (ServerSocketChannel) key.channel(); 109 | 110 | SocketChannel channel = ssc.accept(); 111 | ssc.configureBlocking(false); 112 | ssc.register(selector,SelectionKey.OP_READ); // 准备读 113 | } 114 | 115 | // 读取数据 116 | if(key.isReadable()){ 117 | SocketChannel sc = (SocketChannel) key.channel(); 118 | 119 | ByteBuffer readBuffer = ByteBuffer.allocate(1024); 120 | 121 | int readBytes = sc.read(readBuffer); 122 | 123 | if(readBytes > 0){ 124 | readBuffer.flip(); 125 | 126 | byte[] bytes = new byte[readBuffer.remaining()]; 127 | 128 | readBuffer.get(bytes); 129 | String body = new String(bytes,"UTF-8"); 130 | 131 | System.out.println("The time server receive order:" + body); 132 | String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new Date(System.currentTimeMillis()).toString() : "BAD ORDER"; 133 | 134 | doWrite(sc,currentTime); 135 | }else if(readBytes < 0){ 136 | // 关闭终端 137 | key.cancel(); 138 | sc.close(); 139 | } 140 | } 141 | } 142 | } 143 | 144 | /** 145 | * 向客户端写入数据 146 | * 147 | * @author chenssy 148 | * @date 2017-04-20 149 | * @since v1.0.0 150 | */ 151 | private void doWrite(SocketChannel channel, String response) throws IOException { 152 | if(response != null && response.trim().length() > 0){ 153 | byte[] bytes = response.getBytes(); 154 | 155 | ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length); 156 | 157 | writeBuffer.put(bytes); 158 | writeBuffer.flip(); 159 | channel.write(writeBuffer); 160 | } 161 | } 162 | } 163 | -------------------------------------------------------------------------------- /src/main/java/com/NIO/nio/_1/TimeClientHandle.java: -------------------------------------------------------------------------------- 1 | package com.NIO.nio._1; 2 | 3 | import java.io.IOException; 4 | import java.net.InetSocketAddress; 5 | import java.nio.ByteBuffer; 6 | import java.nio.channels.SelectionKey; 7 | import java.nio.channels.Selector; 8 | import java.nio.channels.SocketChannel; 9 | 10 | public class TimeClientHandle implements Runnable{ 11 | private String host; 12 | 13 | private int port; 14 | 15 | private Selector selector; 16 | 17 | private SocketChannel socketChannel; 18 | 19 | private volatile boolean stop; 20 | 21 | public TimeClientHandle(String host,int port){ 22 | this.host = host == null ? "127.0.0.1" : host; 23 | this.port = port; 24 | 25 | try { 26 | selector = Selector.open(); 27 | socketChannel = SocketChannel.open(); 28 | socketChannel.configureBlocking(false); 29 | } catch (IOException e) { 30 | e.printStackTrace(); 31 | } 32 | } 33 | 34 | 35 | @Override 36 | public void run() { 37 | try { 38 | doConnect(); 39 | } catch (Exception e) { 40 | e.printStackTrace(); 41 | } 42 | 43 | } 44 | 45 | /** 46 | * 链接服务端 47 | * 如果链接成功,则注册到多路复用器上,发送请求消息,读应答 48 | * @author chenming 49 | * @date 2017-04-20 50 | * @since v1.0.0 51 | */ 52 | private void doConnect() throws IOException { 53 | if(socketChannel.connect(new InetSocketAddress(host,port))){ 54 | socketChannel.register(selector, SelectionKey.OP_READ); 55 | dowWrite(socketChannel); 56 | }else{ 57 | socketChannel.register(selector,SelectionKey.OP_CONNECT); 58 | } 59 | } 60 | 61 | /** 62 | * 发送消息 63 | * 64 | * @author chenming 65 | * @date 2017-04-20 66 | * @since v1.0.0 67 | */ 68 | private void dowWrite(SocketChannel socketChannel) throws IOException { 69 | byte[] req = "QUERY TIME ORDER".getBytes(); 70 | 71 | ByteBuffer writeBuffer = ByteBuffer.allocate(req.length); 72 | 73 | writeBuffer.put(req); 74 | writeBuffer.flip(); 75 | 76 | socketChannel.write(writeBuffer); 77 | 78 | if(!writeBuffer.hasRemaining()){ 79 | System.out.println("Send order 2 Server succeed."); 80 | } 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/java_thread/JUC/Atomic/AtomicIntegerArrayTest.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.java_thread.JUC.Atomic; 2 | 3 | import java.util.concurrent.atomic.AtomicIntegerArray; 4 | 5 | /** 6 | * AtomicIntegerArrayTest 7 | * 8 | * @author:chenssy 9 | * @date : 2017/3/28 9:11 10 | */ 11 | public class AtomicIntegerArrayTest{ 12 | private static int[] value = new int[]{1,2,3,4,5}; 13 | 14 | private static AtomicIntegerArray aia = new AtomicIntegerArray(value); 15 | 16 | public static void main(String[] args){ 17 | aia.addAndGet(2,10); //第三个元素 + 10 18 | System.out.println(aia.get(2)); 19 | 20 | //内部进行复制,不会影响原本value 21 | aia.set(1,0); 22 | System.out.println(value[0]); 23 | System.out.println(aia.get(1)); 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/java_thread/JUC/Atomic/AtomicIntegerTest.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.java_thread.JUC.Atomic; 2 | 3 | import java.util.concurrent.atomic.AtomicInteger; 4 | 5 | /** 6 | * AtomicInteger
7 | * 8 | * addAndGet:以原子方式将输入的值与实例的值相加并返回结果
9 | * getAndIncrement:以原子方式将当前值加1,返回的自增之前的值
10 | * lazySet:最终会设置成newValue,使用lazySet设置值后,可能会导致其他线程在之后的一小段时间内还是可以读到旧值
11 | * getAndSet:以原子方式设置为newValue,返回oldValue
12 | * 13 | * @author:chenssy 14 | * @date : 2017/3/28 8:56 15 | */ 16 | public class AtomicIntegerTest { 17 | private static AtomicInteger ai = new AtomicInteger(1); 18 | 19 | public static void main(String[] args){ 20 | System.out.println(ai.getAndIncrement()); 21 | System.out.println(ai.getAndSet(999)); 22 | System.out.println(ai.get()); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/java_thread/JUC/Atomic/AtomicReferenceTest.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.java_thread.JUC.Atomic; 2 | 3 | import java.util.concurrent.atomic.AtomicReference; 4 | 5 | /** 6 | * AtomicReferenceTest 7 | * 8 | * @author:chenssy 9 | * @date : 2017/3/28 9:25 10 | */ 11 | public class AtomicReferenceTest { 12 | private static class User{ 13 | private String name; 14 | private int old; 15 | 16 | public User(String name, int old) { 17 | this.name = name; 18 | this.old = old; 19 | } 20 | 21 | public int getOld() { 22 | return old; 23 | } 24 | 25 | public String getName() { 26 | return name; 27 | } 28 | 29 | @Override 30 | public String toString() { 31 | return "{name: " + getName() + ",old:"+getOld()+"}"; 32 | } 33 | } 34 | 35 | private static AtomicReference atomicReference = new AtomicReference(); 36 | 37 | public static void main(String[] args){ 38 | User user = new User("chenssy",18); 39 | atomicReference.set(user); 40 | System.out.println(atomicReference.get().toString()); 41 | User updateUser = new User("CHENSSY",22); 42 | atomicReference.compareAndSet(user,updateUser); 43 | System.out.println(atomicReference.get().toString()); 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/java_thread/JUC/CAS/Counter.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.java_thread.JUC.CAS; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.concurrent.atomic.AtomicInteger; 6 | 7 | /** 8 | * 演示CAS操作。在java中自旋CAS实现的基本思路是循环进行CAS操作直到成功为止 9 | * 10 | * @author:chenssy 11 | * @date : 2016/8/4 9:09 12 | */ 13 | public class Counter { 14 | private AtomicInteger atomicI = new AtomicInteger(0); 15 | private int i = 0; 16 | /** 17 | * 线程不安全的++ 18 | */ 19 | private void count(){ 20 | i++; 21 | } 22 | 23 | /** 24 | * 使用AtomicInteger线程安全的++ 25 | */ 26 | private void safeCount(){ 27 | for(;;){ 28 | int i = atomicI.get(); 29 | if(atomicI.compareAndSet(i,++i)){ 30 | break; 31 | } 32 | } 33 | } 34 | 35 | public static void main(String[] args) throws InterruptedException { 36 | final Counter cas = new Counter(); 37 | List ts = new ArrayList(600); 38 | long start = System.currentTimeMillis(); 39 | 40 | for(int i = 0 ; i < 100 ; i++){ 41 | Thread j = new Thread(new Runnable() { 42 | @Override 43 | public void run() { 44 | for(int j = 0 ; j < 1000 ; j++){ 45 | cas.count(); 46 | cas.safeCount(); 47 | } 48 | } 49 | }); 50 | ts.add(j); 51 | } 52 | 53 | for(Thread t : ts){ 54 | t.start(); 55 | } 56 | 57 | for(Thread t : ts){ 58 | t.join(); //等待线程执行完成 59 | } 60 | 61 | System.out.println(cas.i); 62 | System.out.println(cas.atomicI.get()); 63 | System.out.println(System.currentTimeMillis() - start); 64 | } 65 | 66 | } 67 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/java_thread/JUC/Lock/AQS/Mutex.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.java_thread.JUC.Lock.AQS; 2 | 3 | import java.util.concurrent.TimeUnit; 4 | import java.util.concurrent.locks.AbstractQueuedSynchronizer; 5 | import java.util.concurrent.locks.Condition; 6 | import java.util.concurrent.locks.Lock; 7 | 8 | /** 9 | * 自定义独占锁
10 | * 11 | * @author:chenssy 12 | * @date : 2016/10/8 8:42 13 | */ 14 | public class Mutex implements Lock{ 15 | 16 | private static class MySync extends AbstractQueuedSynchronizer{ 17 | protected boolean isHeldExclusively(){ 18 | return getState() >= 1; 19 | } 20 | 21 | protected boolean tryAcquire(int acquires){ 22 | if(compareAndSetState(0,acquires)){ 23 | setExclusiveOwnerThread(Thread.currentThread()); 24 | return true; 25 | } 26 | return false; 27 | } 28 | 29 | protected boolean tryRelease(int releases){ 30 | if(getState() == 0){ 31 | throw new IllegalMonitorStateException(); 32 | } 33 | 34 | setExclusiveOwnerThread(null); 35 | setState(0); 36 | return true; 37 | } 38 | 39 | protected Condition newCondition(){ 40 | return new ConditionObject(); 41 | } 42 | } 43 | 44 | /* 45 | * 下面的方法直接使用sync代理即可 46 | */ 47 | private final MySync sync = new MySync(); 48 | 49 | @Override 50 | public void lock() { 51 | sync.acquire(1); 52 | } 53 | 54 | @Override 55 | public void lockInterruptibly() throws InterruptedException { 56 | sync.acquireInterruptibly(1); 57 | } 58 | 59 | @Override 60 | public boolean tryLock() { 61 | return sync.tryAcquire(1); 62 | } 63 | 64 | @Override 65 | public boolean tryLock(long time, TimeUnit unit) throws InterruptedException { 66 | return sync.tryAcquireNanos(1,unit.toNanos(time)); 67 | } 68 | 69 | @Override 70 | public void unlock() { 71 | sync.tryRelease(1); 72 | } 73 | 74 | @Override 75 | public Condition newCondition() { 76 | return sync.newCondition(); 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/java_thread/JUC/Lock/AQS/twinsLock/TwinsLock.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.java_thread.JUC.Lock.AQS.twinsLock; 2 | 3 | import java.util.concurrent.TimeUnit; 4 | import java.util.concurrent.locks.AbstractQueuedSynchronizer; 5 | import java.util.concurrent.locks.Condition; 6 | import java.util.concurrent.locks.Lock; 7 | 8 | /** 9 | * ${todo} 10 | * 11 | * @author:chenssy 12 | * @date : 2016/10/14 9:21 13 | */ 14 | public class TwinsLock implements Lock{ 15 | 16 | private class TwinsSync extends AbstractQueuedSynchronizer{ 17 | public TwinsSync(int count){ 18 | if(count < 0){ 19 | throw new IllegalArgumentException("Count must large than zero."); 20 | } 21 | setState(count); 22 | } 23 | 24 | @Override 25 | protected int tryAcquireShared(int reduceCount) { 26 | for(;;){ 27 | int current = getState(); 28 | int newCount = current - reduceCount; 29 | if(newCount < 0 || compareAndSetState(current,newCount)){ 30 | return newCount; 31 | } 32 | } 33 | } 34 | 35 | @Override 36 | protected boolean tryReleaseShared(int arg) { 37 | for(;;){ 38 | int current = getState(); 39 | int newCount = current - arg; 40 | if(newCount <0 || compareAndSetState(current,newCount)){ 41 | return true; 42 | } 43 | } 44 | 45 | } 46 | } 47 | 48 | private final TwinsSync sync = new TwinsSync(2); 49 | 50 | @Override 51 | public void lock() { 52 | sync.acquireShared(1); 53 | } 54 | 55 | @Override 56 | public void lockInterruptibly() throws InterruptedException { 57 | //doSomething 58 | } 59 | 60 | @Override 61 | public boolean tryLock() { 62 | return false; 63 | } 64 | 65 | @Override 66 | public boolean tryLock(long time, TimeUnit unit) throws InterruptedException { 67 | return false; 68 | } 69 | 70 | @Override 71 | public void unlock() { 72 | sync.tryReleaseShared(1); 73 | } 74 | 75 | @Override 76 | public Condition newCondition() { 77 | return null; 78 | } 79 | 80 | } 81 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/java_thread/JUC/Lock/AQS/twinsLock/TwinsLockTest.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.java_thread.JUC.Lock.AQS.twinsLock; 2 | 3 | import java.util.concurrent.TimeUnit; 4 | import java.util.concurrent.locks.Lock; 5 | 6 | /** 7 | * ${todo} 8 | * 9 | * @author:chenssy 10 | * @date : 2016/10/14 10:44 11 | */ 12 | public class TwinsLockTest { 13 | public static void main(String args[]) throws InterruptedException { 14 | final Lock lock = new TwinsLock(); 15 | 16 | class Work extends Thread{ 17 | @Override 18 | public void run() { 19 | lock.lock(); 20 | 21 | try { 22 | TimeUnit.SECONDS.sleep(1); 23 | System.out.println(Thread.currentThread().getName()); 24 | TimeUnit.SECONDS.sleep(1); 25 | } catch (InterruptedException e) { 26 | e.printStackTrace(); 27 | } finally { 28 | lock.unlock(); 29 | } 30 | } 31 | } 32 | 33 | for(int i = 0 ; i < 10 ; i++){ 34 | Work work = new Work(); 35 | work.setDaemon(true); 36 | work.start(); 37 | } 38 | 39 | for(int i = 0 ; i < 10 ; i++){ 40 | TimeUnit.SECONDS.sleep(1); 41 | //应该是成对输出!! 42 | System.out.println(""); 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/java_thread/JUC/Lock/ReentrantLock/_1/Job.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.java_thread.JUC.Lock.ReentrantLock._1; 2 | 3 | public class Job implements Runnable{ 4 | private PrintQueue printQueue; 5 | 6 | public Job(PrintQueue printQueue){ 7 | this.printQueue = printQueue; 8 | } 9 | 10 | @Override 11 | public void run() { 12 | printQueue.printJob(new Object()); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/java_thread/JUC/Lock/ReentrantLock/_1/PrintQueue.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.java_thread.JUC.Lock.ReentrantLock._1; 2 | 3 | import java.util.concurrent.locks.Lock; 4 | import java.util.concurrent.locks.ReentrantLock; 5 | 6 | public class PrintQueue { 7 | private final Lock queueLock = new ReentrantLock(); 8 | 9 | public void printJob(Object document) { 10 | try { 11 | queueLock.lock(); 12 | System.out.println(Thread.currentThread().getName() + ": Going to print a document"); 13 | Long duration = (long) (Math.random() * 10000); 14 | System.out.println(Thread.currentThread().getName() + ":PrintQueue: Printing a Job during " + (duration / 1000) + " seconds"); 15 | Thread.sleep(duration); 16 | System.out.printf(Thread.currentThread().getName() + ": The document has been printed\n"); 17 | } catch (InterruptedException e) { 18 | e.printStackTrace(); 19 | } finally { 20 | queueLock.unlock(); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/java_thread/JUC/Lock/ReentrantLock/_1/Test.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.java_thread.JUC.Lock.ReentrantLock._1; 2 | 3 | public class Test { 4 | public static void main(String[] args) { 5 | PrintQueue printQueue = new PrintQueue(); 6 | 7 | Thread thread[] = new Thread[10]; 8 | for (int i = 0; i < 10; i++) { 9 | thread[i] = new Thread(new Job(printQueue), "Thread " + i); 10 | } 11 | 12 | for (int i = 0; i < 10; i++) { 13 | thread[i].start(); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/java_thread/JUC/Lock/ReentrantReadWriteLock/PricesInfo.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.java_thread.JUC.Lock.ReentrantReadWriteLock; 2 | 3 | import java.util.concurrent.locks.ReadWriteLock; 4 | import java.util.concurrent.locks.ReentrantReadWriteLock; 5 | 6 | public class PricesInfo { 7 | private double price1; 8 | private double price2; 9 | 10 | private ReadWriteLock lock; 11 | 12 | public PricesInfo(){ 13 | price1 = 1.0; 14 | price2 = 2.0; 15 | 16 | lock = new ReentrantReadWriteLock(); 17 | } 18 | 19 | public double getPrice1(){ 20 | lock.readLock().lock(); 21 | double value = price1; 22 | lock.readLock().unlock(); 23 | return value; 24 | } 25 | 26 | public double getPrice2(){ 27 | lock.readLock().lock(); 28 | double value = price2; 29 | lock.readLock().unlock(); 30 | return value; 31 | } 32 | 33 | public void setPrices(double price1, double price2){ 34 | lock.writeLock().lock(); 35 | this.price1 = price1; 36 | this.price2 = price2; 37 | lock.writeLock().unlock(); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/java_thread/JUC/Lock/ReentrantReadWriteLock/Reader.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.java_thread.JUC.Lock.ReentrantReadWriteLock; 2 | 3 | public class Reader implements Runnable{ 4 | 5 | private PricesInfo pricesInfo; 6 | 7 | public Reader(PricesInfo pricesInfo){ 8 | this.pricesInfo = pricesInfo; 9 | } 10 | 11 | @Override 12 | public void run() { 13 | for (int i = 0; i < 10; i++) { 14 | System.out.println(Thread.currentThread().getName() + "--Price 1:" + pricesInfo.getPrice1()); 15 | System.out.println(Thread.currentThread().getName() + "--Price 1:" + pricesInfo.getPrice2()); 16 | } 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/java_thread/JUC/Lock/ReentrantReadWriteLock/Test.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.java_thread.JUC.Lock.ReentrantReadWriteLock; 2 | 3 | public class Test { 4 | public static void main(String[] args) { 5 | PricesInfo pricesInfo = new PricesInfo(); 6 | 7 | Reader[] readers = new Reader[5]; 8 | Thread[] readerThread = new Thread[5]; 9 | for (int i=0; i<5; i++){ 10 | readers[i]=new Reader(pricesInfo); 11 | readerThread[i]=new Thread(readers[i]); 12 | } 13 | 14 | Writer writer=new Writer(pricesInfo); 15 | Thread threadWriter=new Thread(writer); 16 | 17 | for (int i=0; i<5; i++){ 18 | readerThread[i].start(); 19 | } 20 | threadWriter.start(); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/java_thread/JUC/Lock/ReentrantReadWriteLock/Writer.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.java_thread.JUC.Lock.ReentrantReadWriteLock; 2 | 3 | public class Writer implements Runnable{ 4 | private PricesInfo pricesInfo; 5 | 6 | public Writer(PricesInfo pricesInfo){ 7 | this.pricesInfo = pricesInfo; 8 | } 9 | 10 | @Override 11 | public void run() { 12 | for (int i=0; i<3; i++) { 13 | System.out.printf("Writer: Attempt to modify the prices.\n"); 14 | pricesInfo.setPrices(Math.random()*10, Math.random()*8); 15 | System.out.printf("Writer: Prices have been modified.\n"); 16 | try { 17 | Thread.sleep(2); 18 | } catch (InterruptedException e) { 19 | e.printStackTrace(); 20 | } 21 | } 22 | 23 | } 24 | 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/java_thread/JUC/Lock/condition/Customer.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.java_thread.JUC.Lock.condition; 2 | 3 | public class Customer { 4 | private Depot depot; 5 | 6 | public Customer(Depot depot) { 7 | this.depot = depot; 8 | } 9 | 10 | public void consume(final int value) { 11 | new Thread() { 12 | public void run() { 13 | depot.get(value); 14 | } 15 | }.start(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/java_thread/JUC/Lock/condition/Depot.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.java_thread.JUC.Lock.condition; 2 | 3 | import java.util.concurrent.locks.Condition; 4 | import java.util.concurrent.locks.Lock; 5 | import java.util.concurrent.locks.ReentrantLock; 6 | 7 | public class Depot { 8 | private int depotSize; // �ֿ��С 9 | private Lock lock; // ��ռ�� 10 | private int capaity; // �ֿ����� 11 | 12 | private Condition fullCondition; 13 | private Condition emptyCondition; 14 | 15 | public Depot() { 16 | this.depotSize = 0; 17 | this.lock = new ReentrantLock(); 18 | this.capaity = 15; 19 | this.fullCondition = lock.newCondition(); 20 | this.emptyCondition = lock.newCondition(); 21 | } 22 | 23 | /** 24 | * ��Ʒ��� 25 | * 26 | * @param value 27 | */ 28 | public void put(int value) { 29 | lock.lock(); 30 | try { 31 | int left = value; 32 | while (left > 0) { 33 | // �������ʱ��������ߡ��ȴ�����ߡ���� 34 | while (depotSize >= capaity) { 35 | fullCondition.await(); 36 | } 37 | // ��ȡʵ�����������Ԥ�ƿ�棨�ֿ����п�� + ��������� > �ֿ����� ? �ֿ����� - �ֿ����п�� : ������� 38 | // depotSize left capaity capaity - depotSize left 39 | int inc = depotSize + left > capaity ? capaity - depotSize 40 | : left; 41 | depotSize += inc; 42 | left -= inc; 43 | System.out.println(Thread.currentThread().getName() 44 | + "----Ҫ�������: " + value + ";;ʵ�����������" + inc 45 | + ";;�ֿ����������" + depotSize + ";;û�����������" + left); 46 | 47 | // ֪ͨ����߿�������� 48 | emptyCondition.signal(); 49 | } 50 | } catch (InterruptedException e) { 51 | } finally { 52 | lock.unlock(); 53 | } 54 | } 55 | 56 | /** 57 | * ��Ʒ���� 58 | * 59 | * @param value 60 | */ 61 | public void get(int value) { 62 | lock.lock(); 63 | try { 64 | int left = value; 65 | while (left > 0) { 66 | // �ֿ��ѿգ�������ߡ��ȴ�����ߡ������� 67 | while (depotSize <= 0) { 68 | emptyCondition.await(); 69 | } 70 | // ʵ����� �ֿ������� < Ҫ��ѵ����� ? �ֿ������� : Ҫ��ѵ����� 71 | int dec = depotSize < left ? depotSize : left; 72 | depotSize -= dec; 73 | left -= dec; 74 | System.out.println(Thread.currentThread().getName() 75 | + "----Ҫ��ѵ�������" + value + ";;ʵ����ѵ�����: " + dec 76 | + ";;�ֿ��ִ�������" + depotSize + ";;�ж��ټ���Ʒû����ѣ�" + left); 77 | 78 | // ֪ͨ����߿�������� 79 | fullCondition.signal(); 80 | } 81 | } catch (InterruptedException e) { 82 | e.printStackTrace(); 83 | } finally { 84 | lock.unlock(); 85 | } 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/java_thread/JUC/Lock/condition/Producer.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.java_thread.JUC.Lock.condition; 2 | 3 | public class Producer { 4 | private Depot depot; 5 | 6 | public Producer(Depot depot){ 7 | this.depot = depot; 8 | } 9 | 10 | public void produce(final int value){ 11 | new Thread(){ 12 | public void run(){ 13 | depot.put(value); 14 | } 15 | }.start(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/java_thread/JUC/Lock/condition/Test.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.java_thread.JUC.Lock.condition; 2 | 3 | public class Test { 4 | public static void main(String[] args) { 5 | Depot depot = new Depot(); 6 | 7 | Producer producer = new Producer(depot); 8 | Customer customer = new Customer(depot); 9 | 10 | producer.produce(10); 11 | customer.consume(5); 12 | producer.produce(15); 13 | customer.consume(10); 14 | customer.consume(15); 15 | producer.produce(10); 16 | } 17 | } -------------------------------------------------------------------------------- /src/main/java/com/javaCore/java_thread/JUC/ThreadUtils/CountDownLatch/Conference.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.java_thread.JUC.CountDownLatch; 2 | 3 | import java.util.concurrent.CountDownLatch; 4 | 5 | public class Conference implements Runnable{ 6 | private final CountDownLatch countDown; 7 | 8 | public Conference(int count){ 9 | countDown = new CountDownLatch(count); 10 | } 11 | 12 | /** 13 | * �����Ա�������arrive����������һ��CountDownLatch����countDown�������������-1 14 | * @author:chenssy 15 | * @data:2015��9��6�� 16 | * 17 | * @param name 18 | */ 19 | public void arrive(String name){ 20 | System.out.println(name + "����....."); 21 | //����countDown()������� - 1 22 | countDown.countDown(); 23 | System.out.println("���� " + countDown.getCount() + "û�е���..."); 24 | } 25 | 26 | @Override 27 | public void run() { 28 | System.out.println("׼�����ᣬ�μӻ�����Ա����Ϊ��" + countDown.getCount()); 29 | //����await()�ȴ����е������Ա���� 30 | try { 31 | countDown.await(); 32 | } catch (InterruptedException e) { 33 | } 34 | System.out.println("������Ա�Ѿ�������鿪ʼ....."); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/java_thread/JUC/ThreadUtils/CountDownLatch/Participater.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.java_thread.JUC.CountDownLatch; 2 | 3 | public class Participater implements Runnable{ 4 | private String name; 5 | private Conference conference; 6 | 7 | public Participater(String name,Conference conference){ 8 | this.name = name; 9 | this.conference = conference; 10 | } 11 | 12 | @Override 13 | public void run() { 14 | conference.arrive(name); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/java_thread/JUC/ThreadUtils/CountDownLatch/Test.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.java_thread.JUC.CountDownLatch; 2 | 3 | public class Test { 4 | public static void main(String[] args) { 5 | //�����������̣߳��ȴ������Ա�μӻ��� 6 | Conference conference = new Conference(3); 7 | new Thread(conference).start(); 8 | 9 | for(int i = 0 ; i < 3 ; i++){ 10 | Participater participater = new Participater("chenssy-0" + i , conference); 11 | Thread thread = new Thread(participater); 12 | thread.start(); 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/java_thread/JUC/ThreadUtils/CyclicBarrier/CyclicBarrierTest_1.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.java_thread.JUC.CyclicBarrier; 2 | 3 | import java.util.concurrent.CyclicBarrier; 4 | 5 | public class CyclicBarrierTest_1 { 6 | private static CyclicBarrier barrier; 7 | 8 | static class threadTest1 extends Thread{ 9 | public void run() { 10 | System.out.println(Thread.currentThread().getName() + "�ﵽ..."); 11 | try { 12 | barrier.await(); 13 | } catch (Exception e) { 14 | e.printStackTrace(); 15 | } 16 | System.out.println(Thread.currentThread().getName() + "ִ�����..."); 17 | } 18 | } 19 | 20 | public static void main(String[] args) { 21 | barrier = new CyclicBarrier(5); 22 | for(int i = 1 ; i <= 5 ; i++){ 23 | new threadTest1().start(); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/java_thread/JUC/ThreadUtils/CyclicBarrier/CyclicBarrierTest_2.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.java_thread.JUC.CyclicBarrier; 2 | 3 | import java.util.concurrent.CyclicBarrier; 4 | 5 | public class CyclicBarrierTest_2 { 6 | private static CyclicBarrier barrier; 7 | 8 | static class threadTest1 extends Thread{ 9 | public void run() { 10 | System.out.println(Thread.currentThread().getName() + "�ﵽ..."); 11 | try { 12 | barrier.await(); 13 | } catch (Exception e) { 14 | e.printStackTrace(); 15 | } 16 | System.out.println(Thread.currentThread().getName() + "ִ�����..."); 17 | } 18 | } 19 | 20 | public static void main(String[] args) { 21 | barrier = new CyclicBarrier(5,new Runnable() { 22 | 23 | @Override 24 | public void run() { 25 | System.out.println("ִ��CyclicBarrier�е�����....."); 26 | } 27 | }); 28 | for(int i = 1 ; i <= 5 ; i++){ 29 | new threadTest1().start(); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/java_thread/JUC/ThreadUtils/Exchanger/Consumer.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.java_thread.JUC.ThreadUtils.Exchanger; 2 | 3 | import java.util.List; 4 | import java.util.concurrent.Exchanger; 5 | 6 | public class Consumer implements Runnable{ 7 | private List buffer; 8 | 9 | private final Exchanger> exchanger; 10 | 11 | public Consumer(List buffer,Exchanger> exchanger){ 12 | this.buffer = buffer; 13 | this.exchanger = exchanger; 14 | } 15 | 16 | @Override 17 | public void run() { 18 | int cycle = 1; 19 | for(int i = 0 ; i < 10 ; i++){ 20 | System.out.println("Consumer : Cycle :" + cycle); 21 | 22 | //����exchange()������߽�����ݽ��� 23 | try { 24 | buffer = exchanger.exchange(buffer); 25 | } catch (InterruptedException e) { 26 | e.printStackTrace(); 27 | } 28 | System.out.println("Consumer :" + buffer.size()); 29 | for(int j = 0 ; j < 10 ; j++){ 30 | System.out.println("Consumer : " + buffer.get(0)); 31 | buffer.remove(0); 32 | } 33 | cycle++ ; 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/java_thread/JUC/ThreadUtils/Exchanger/Producer.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.java_thread.JUC.ThreadUtils.Exchanger; 2 | 3 | import java.util.List; 4 | import java.util.concurrent.Exchanger; 5 | 6 | /** 7 | * ����� 8 | * @Project:javaConcurrency 9 | * @file:Producer.java 10 | * 11 | * @Author:chenssy 12 | * @email:chenssy995812509@163.com 13 | * @url : http://cmsblogs.com 14 | * @qq : 122448894 15 | * 16 | * @data:2015��9��21�� 17 | */ 18 | public class Producer implements Runnable{ 19 | 20 | /** 21 | * ����ߺ�����߽��н�������ݽṹ 22 | */ 23 | private List buffer; 24 | 25 | /** 26 | * ͬ������ߺ�����ߵĽ������� 27 | */ 28 | private final Exchanger> exchanger; 29 | 30 | Producer(List buffer,Exchanger> exchanger){ 31 | this.buffer = buffer; 32 | this.exchanger = exchanger; 33 | } 34 | 35 | @Override 36 | public void run() { 37 | int cycle = 1; 38 | for(int i = 0 ; i < 10 ; i++){ 39 | System.out.println("Producer : Cycle :" + cycle); 40 | for(int j = 0 ; j < 10 ; j++){ 41 | String message = "Event " + ((i * 10 ) + j); 42 | System.out.println("Producer : " + message); 43 | buffer.add(message); 44 | } 45 | 46 | //����exchange()������߽�����ݽ��� 47 | try { 48 | buffer = exchanger.exchange(buffer); 49 | } catch (InterruptedException e) { 50 | e.printStackTrace(); 51 | } 52 | System.out.println("Producer :" + buffer.size()); 53 | cycle++ ; 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/java_thread/JUC/ThreadUtils/Exchanger/Test.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.java_thread.JUC.ThreadUtils.Exchanger; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.concurrent.Exchanger; 6 | 7 | public class Test { 8 | public static void main(String[] args) { 9 | List buffer1 = new ArrayList(); 10 | List buffer2 = new ArrayList(); 11 | 12 | Exchanger> exchanger = new Exchanger>(); 13 | 14 | Producer producer = new Producer(buffer1, exchanger); 15 | Consumer consumer = new Consumer(buffer2, exchanger); 16 | 17 | Thread thread1 = new Thread(producer); 18 | Thread thread2 = new Thread(consumer); 19 | 20 | thread1.start(); 21 | thread2.start(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/java_thread/JUC/ThreadUtils/Phaser/PhaserTest_1.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.java_thread.JUC.Phaser; 2 | 3 | import java.util.concurrent.Phaser; 4 | 5 | public class PhaserTest_1 { 6 | public static void main(String[] args) { 7 | Phaser phaser = new Phaser(5); 8 | 9 | for(int i = 0 ; i < 5 ; i++){ 10 | Task_01 task_01 = new Task_01(phaser); 11 | Thread thread = new Thread(task_01, "PhaseTest_" + i); 12 | thread.start(); 13 | } 14 | } 15 | 16 | static class Task_01 implements Runnable{ 17 | private final Phaser phaser; 18 | 19 | public Task_01(Phaser phaser){ 20 | this.phaser = phaser; 21 | } 22 | 23 | @Override 24 | public void run() { 25 | System.out.println(Thread.currentThread().getName() + "ִ��������ɣ��ȴ���������ִ��......"); 26 | //�ȴ���������ִ����� 27 | phaser.arriveAndAwaitAdvance(); 28 | System.out.println(Thread.currentThread().getName() + "����ִ������..."); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/java_thread/JUC/ThreadUtils/Phaser/PhaserTest_2.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.java_thread.JUC.Phaser; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.IOException; 5 | import java.io.InputStreamReader; 6 | import java.util.concurrent.Phaser; 7 | 8 | public class PhaserTest_2 { 9 | public static void main(String[] args) throws InterruptedException, IOException { 10 | Phaser phaser = new Phaser(6); 11 | int i = 0; 12 | for(i = 1 ; i <= 6 ; i++){ 13 | Task_02 task = new Task_02(phaser); 14 | Thread thread = new Thread(task,"task_" + i); 15 | thread.start(); 16 | } 17 | System.out.println("Press ENTER to continue"); 18 | BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); 19 | reader.readLine(); 20 | //���»س���ִ�� 21 | phaser.arriveAndDeregister(); 22 | } 23 | 24 | 25 | static class Task_02 implements Runnable{ 26 | private final Phaser phaser; 27 | 28 | public Task_02(Phaser phaser){ 29 | this.phaser = phaser; 30 | } 31 | 32 | 33 | @Override 34 | public void run() { 35 | System.out.println(Thread.currentThread().getName() + "��ʼִ������..."); 36 | phaser.arriveAndAwaitAdvance(); 37 | System.out.println(Thread.currentThread().getName() + "����ִ������..."); 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/java_thread/JUC/ThreadUtils/Phaser/PhaserTest_3.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.java_thread.JUC.Phaser; 2 | 3 | import java.util.concurrent.Phaser; 4 | 5 | public class PhaserTest_3 { 6 | public static void main(String[] args) { 7 | Phaser phaser = new Phaser(3){ 8 | /** 9 | * registeredParties:�߳�ע������� 10 | * phase:����÷������߳��� 11 | */ 12 | protected boolean onAdvance(int phase, int registeredParties) { 13 | System.out.println(Thread.currentThread().getName() + "ִ��onAdvance����.....;phase:" + phase + "registeredParties=" + registeredParties); 14 | return phase == 2; 15 | } 16 | }; 17 | 18 | for(int i = 0 ; i < 3 ; i++){ 19 | Task_03 task = new Task_03(phaser); 20 | Thread thread = new Thread(task,"task_" + i); 21 | thread.start(); 22 | } 23 | while(!phaser.isTerminated()){ 24 | phaser.arriveAndAwaitAdvance(); //���߳�һֱ�ȴ� 25 | } 26 | System.out.println("���߳������Ѿ�����...."); 27 | } 28 | 29 | static class Task_03 implements Runnable{ 30 | private final Phaser phaser; 31 | 32 | public Task_03(Phaser phaser){ 33 | this.phaser = phaser; 34 | } 35 | 36 | @Override 37 | public void run() { 38 | do{ 39 | try { 40 | Thread.sleep(500); 41 | } catch (InterruptedException e) { 42 | e.printStackTrace(); 43 | } 44 | System.out.println(Thread.currentThread().getName() + "��ʼִ������..."); 45 | phaser.arriveAndAwaitAdvance(); 46 | }while(!phaser.isTerminated()); 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/java_thread/JUC/ThreadUtils/Phaser/PhaserTest_4.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.java_thread.JUC.Phaser; 2 | 3 | import java.util.concurrent.Phaser; 4 | 5 | import com.javaCore.java_thread.JUC.Phaser.PhaserTest_3.Task_03; 6 | 7 | public class PhaserTest_4 { 8 | public static void main(String[] args) { 9 | final int phaseToTerminate = 3; 10 | Phaser phaser = new Phaser(5){ 11 | protected boolean onAdvance(int phase, int registeredParties) { 12 | System.out.println("执行onAdvance方法....."); 13 | return phase >= phaseToTerminate || registeredParties == 0; 14 | } 15 | }; 16 | 17 | for(int i = 0 ; i < 5 ; i++){ 18 | Task_03 task = new Task_03(phaser); 19 | Thread thread = new Thread(task,"task_" + i); 20 | thread.start(); 21 | } 22 | 23 | phaser.register(); 24 | while(!phaser.isTerminated()){ 25 | phaser.arriveAndAwaitAdvance(); 26 | }; 27 | 28 | System.out.println("主线程任务已经结束...."); 29 | } 30 | 31 | static class Task_04 implements Runnable{ 32 | private final Phaser phaser; 33 | 34 | public Task_04(Phaser phaser){ 35 | this.phaser = phaser; 36 | } 37 | 38 | @Override 39 | public void run() { 40 | do{ 41 | try { 42 | Thread.sleep(500); 43 | } catch (InterruptedException e) { 44 | e.printStackTrace(); 45 | } 46 | System.out.println(Thread.currentThread().getName() + "开始执行任务..."); 47 | phaser.arriveAndAwaitAdvance(); 48 | }while(!phaser.isTerminated()); 49 | } 50 | 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/java_thread/JUC/ThreadUtils/Phaser/PhaserTest_5.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.java_thread.JUC.Phaser; 2 | 3 | import java.util.concurrent.Phaser; 4 | 5 | public class PhaserTest_5 { 6 | public static void main(String[] args) { 7 | Phaser phaser = new Phaser(1); //�൱��CountDownLatch(1) 8 | 9 | //��������� 10 | for(int i = 0 ; i < 3 ; i++){ 11 | Task_05 task = new Task_05(phaser); 12 | Thread thread = new Thread(task,"PhaseTest_" + i); 13 | thread.start(); 14 | } 15 | 16 | try { 17 | //�ȴ�3�� 18 | Thread.sleep(3000); 19 | } catch (InterruptedException e) { 20 | e.printStackTrace(); 21 | } 22 | phaser.arrive(); //countDownLatch.countDown() 23 | } 24 | 25 | static class Task_05 implements Runnable{ 26 | private final Phaser phaser; 27 | 28 | Task_05(Phaser phaser){ 29 | this.phaser = phaser; 30 | } 31 | 32 | @Override 33 | public void run() { 34 | phaser.awaitAdvance(phaser.getPhase()); //countDownLatch.await() 35 | System.out.println(Thread.currentThread().getName() + "ִ������..."); 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/java_thread/JUC/ThreadUtils/Phaser/PhaserTest_6.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.java_thread.JUC.Phaser; 2 | 3 | import java.util.concurrent.Phaser; 4 | 5 | public class PhaserTest_6 { 6 | public static void main(String[] args) { 7 | Phaser phaser = new Phaser(3){ 8 | protected boolean onAdvance(int phase, int registeredParties) { 9 | System.out.println("------------------------����ҷָ��:phase=" + phase + ";registeredParties=" 10 | + registeredParties + "------------------------"); 11 | return registeredParties == 1; 12 | } 13 | }; 14 | 15 | for(int i = 0 ; i < 3 ; i++){ 16 | Thread thread = new Thread(new Task_06(phaser,i),"PhaserTest_" + i); 17 | thread.start(); 18 | } 19 | 20 | do{ 21 | phaser.arriveAndAwaitAdvance(); //���̵߳ȴ��������������.. 22 | }while(!phaser.isTerminated()); 23 | 24 | System.out.println("����ִ�����....."); 25 | } 26 | 27 | static class Task_06 implements Runnable{ 28 | private final Phaser phaser; 29 | private int i ; 30 | Task_06(Phaser phaser,int i ){ 31 | this.phaser = phaser; 32 | this.i = i; 33 | } 34 | 35 | @Override 36 | public void run() { 37 | System.out.println("----ִ��������:" + Thread.currentThread().getName() + "; i = " + i); 38 | //��������� 39 | while(true){ 40 | i++; 41 | if(i == 5){ //��i == 5ʱ�����������Phaser�����߳� - 1 42 | phaser.arriveAndAwaitAdvance(); 43 | break; 44 | } 45 | else{ 46 | //�ȴ������̵߳���׶��յ㣬��һ�������һ���׶� 47 | System.out.println(Thread.currentThread().getName() + "; i = " + i); 48 | phaser.arriveAndAwaitAdvance(); 49 | } 50 | } 51 | } 52 | 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/java_thread/JUC/ThreadUtils/Phaser/PhaserTest_7.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.java_thread.JUC.Phaser; 2 | 3 | import java.util.concurrent.Phaser; 4 | 5 | public class PhaserTest_7 { 6 | private static final int TASKS_PER_PHASER = 4; 7 | 8 | public static void main(String[] args) { 9 | final int phaseToTerminate = 3; 10 | 11 | Phaser phaser = new Phaser(){ 12 | @Override 13 | protected boolean onAdvance(int phase, int registeredParties) { 14 | System.out.println("====== " + phase + " ======"); 15 | return phase == phaseToTerminate || registeredParties == 0; 16 | } 17 | }; 18 | 19 | final Task_07[] tasks = new Task_07[10]; 20 | Builder(tasks,0,tasks.length,phaser); 21 | 22 | for (int i = 0; i < tasks.length; i++) { 23 | System.out.println("starting thread, id: " + i); 24 | final Thread thread = new Thread(tasks[i]); 25 | thread.start(); 26 | } 27 | } 28 | 29 | private static void Builder(Task_07[] tasks, int lo, int hi, 30 | Phaser phaser) { 31 | if (hi - lo > TASKS_PER_PHASER) { 32 | for (int i = lo; i < hi; i += TASKS_PER_PHASER) { 33 | int j = Math.min(i + TASKS_PER_PHASER, hi); 34 | Builder(tasks, i, j, new Phaser(phaser)); 35 | } 36 | } else { 37 | for (int i = lo; i < hi; ++i) 38 | tasks[i] = new Task_07(i, phaser); 39 | } 40 | } 41 | 42 | static class Task_07 implements Runnable{ 43 | private final Phaser phaser; 44 | private int i ; 45 | 46 | Task_07(int i , Phaser phaser){ 47 | this.i = i; 48 | this.phaser = phaser; 49 | this.phaser.register(); 50 | } 51 | @Override 52 | public void run() { 53 | while (!phaser.isTerminated()) { 54 | try { 55 | Thread.sleep(200); 56 | } catch (InterruptedException e) { 57 | } 58 | System.out.println("in Task.run(), phase: " + phaser.getPhase() + ", id: " + this.i); 59 | phaser.arriveAndAwaitAdvance(); 60 | } 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/java_thread/JUC/ThreadUtils/Semaphore/Job.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.java_thread.JUC.Semaphore; 2 | 3 | /** 4 | * 5 | * @Project:javaConcurrency 6 | * @file:Job.java 7 | * 8 | * @Author:chenssy 9 | * @email:chenssy995812509@163.com 10 | * @url : http://cmsblogs.com 11 | * @qq : 122448894 12 | * 13 | * @data:2015��9��6�� 14 | */ 15 | public class Job implements Runnable{ 16 | private PrintQueue printQueue; 17 | 18 | public Job(PrintQueue printQueue){ 19 | this.printQueue = printQueue; 20 | } 21 | 22 | @Override 23 | public void run() { 24 | System.out.println(Thread.currentThread().getName() + " Going to print a job"); 25 | printQueue.printJob(new Object()); 26 | System.out.println(Thread.currentThread().getName() + " the document has bean printed"); 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/java_thread/JUC/ThreadUtils/Semaphore/PrintQueue.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.java_thread.JUC.Semaphore; 2 | 3 | import java.util.concurrent.Semaphore; 4 | 5 | /** 6 | * ��ӡ���� 7 | * @Project:javaConcurrency 8 | * @file:PrintQueue.java 9 | * 10 | * @Author:chenssy 11 | * @email:chenssy995812509@163.com 12 | * @url : http://cmsblogs.com 13 | * @qq : 122448894 14 | * 15 | * @data:2015��9��6�� 16 | */ 17 | public class PrintQueue { 18 | private final Semaphore semaphore; //�����ź��� 19 | 20 | public PrintQueue(){ 21 | semaphore = new Semaphore(1); 22 | } 23 | 24 | public void printJob(Object document){ 25 | try { 26 | semaphore.acquire();//����acquire��ȡ�ź��� 27 | long duration = (long) (Math.random() * 10); 28 | System.out.println( Thread.currentThread().getName() + 29 | "PrintQueue : Printing a job during " + duration); 30 | Thread.sleep(duration); 31 | } catch (InterruptedException e) { 32 | e.printStackTrace(); 33 | } finally{ 34 | semaphore.release(); //�ͷ��ź��� 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/java_thread/JUC/ThreadUtils/Semaphore/Test.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.java_thread.JUC.Semaphore; 2 | 3 | public class Test { 4 | public static void main(String[] args) { 5 | Thread[] threads = new Thread[5]; 6 | 7 | PrintQueue printQueue = new PrintQueue(); 8 | 9 | for(int i = 0 ; i < 5 ; i++){ 10 | threads[i] = new Thread(new Job(printQueue),"Thread_" + i); 11 | } 12 | 13 | for(int i = 0 ; i < 5 ; i++){ 14 | threads[i].start(); 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/java_thread/JUC/concurrentCollection/ConcurrentHashMap/ConcurrentHashMapTest.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.java_thread.JUC.concurrentCollection.ConcurrentHashMap; 2 | 3 | import java.util.concurrent.ConcurrentHashMap; 4 | 5 | public class ConcurrentHashMapTest { 6 | @SuppressWarnings("rawtypes") 7 | private ConcurrentHashMap maps = new ConcurrentHashMap(); 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/java_thread/JUC/concurrentCollection/CopyOnWriteArrayList/CopyOnWriteArrayListTest.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.java_thread.JUC.concurrentCollection.CopyOnWriteArrayList; 2 | 3 | import java.util.Iterator; 4 | import java.util.List; 5 | import java.util.concurrent.CopyOnWriteArrayList; 6 | 7 | public class CopyOnWriteArrayListTest { 8 | private static List list = new CopyOnWriteArrayList(); 9 | 10 | public static void main(String[] args) { 11 | new MyThread("testA").start(); 12 | new MyThread("testB").start(); 13 | } 14 | 15 | private static class MyThread extends Thread{ 16 | public MyThread(String name) { 17 | super(name); 18 | } 19 | 20 | @Override 21 | public void run() { 22 | for(int i = 0 ; i < 10 ; i++){ 23 | list.add(Thread.currentThread().getName() + "-" + i ); 24 | printAll(); 25 | } 26 | } 27 | } 28 | 29 | private static void printAll() { 30 | Iterator iterator = list.iterator(); 31 | while(iterator.hasNext()){ 32 | String value = iterator.next(); 33 | System.out.print(value + " "); 34 | } 35 | System.out.println(); 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/java_thread/JUC/concurrentCollection/CopyOnWriteArraySet/CopyOnWriteArraySetTest.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.java_thread.JUC.concurrentCollection.CopyOnWriteArraySet; 2 | 3 | import java.util.Iterator; 4 | import java.util.Set; 5 | import java.util.concurrent.CopyOnWriteArraySet; 6 | 7 | public class CopyOnWriteArraySetTest { 8 | private static Set setes = new CopyOnWriteArraySet(); 9 | 10 | public static void main(String[] args) { 11 | new MyThread("testA").start(); 12 | new MyThread("testB").start(); 13 | } 14 | 15 | private static class MyThread extends Thread{ 16 | MyThread(String name){ 17 | super(name); 18 | } 19 | public void run(){ 20 | for(int i = 0 ; i < 5 ; i++){ 21 | setes.add(Thread.currentThread().getName() + "--" + i); 22 | printAll(); 23 | } 24 | } 25 | } 26 | 27 | public static void printAll() { 28 | Iterator iterator = setes.iterator(); 29 | while(iterator.hasNext()){ 30 | System.out.print(iterator.next() + " "); 31 | } 32 | System.out.println(""); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/java_thread/basic/InterruptedThread.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.java_thread.basic; 2 | 3 | import java.util.concurrent.TimeUnit; 4 | 5 | /** 6 | * 线程中断测试
7 | * 线程A不停地休眠,线程B一直运行,然后进行中断操作,观察两个线程的中断标识
8 | * 9 | *InterruptedException:当线程在活动之前或活动期间处于正在等待、休眠或占用状态且该线程被中断时,抛出该异常 10 | * 11 | * @author:chenssy 12 | * @date : 2016/8/16 8:44 13 | */ 14 | public class InterruptedThread { 15 | static class SleepThread implements Runnable{ 16 | @Override 17 | public void run() { 18 | while(true){ 19 | try { 20 | TimeUnit.SECONDS.sleep(10); //不停地休眠 21 | } catch (InterruptedException e) { 22 | e.printStackTrace(); 23 | } 24 | } 25 | } 26 | } 27 | 28 | static class BusyThread implements Runnable{ 29 | @Override 30 | public void run() { 31 | while(true){ 32 | //一直运行 33 | } 34 | } 35 | } 36 | 37 | 38 | public static void main(String[] args) throws InterruptedException { 39 | Thread sleepThread = new Thread(new SleepThread(),"SleepThread"); 40 | Thread busyThread = new Thread(new BusyThread(),"BusyThread"); 41 | 42 | busyThread.setDaemon(true); //设置为Daemon模式 43 | sleepThread.start(); 44 | busyThread.start(); 45 | 46 | //休眠五秒,两个线程充分运行 47 | TimeUnit.SECONDS.sleep(5); 48 | 49 | //终止线程 50 | sleepThread.interrupt(); 51 | busyThread.interrupt(); 52 | 53 | //观看终止状态 54 | System.out.println("SleepThread interrupted is " + sleepThread.isInterrupted()); 55 | System.out.println("BusyThread interrupted is " + busyThread.isInterrupted()); 56 | 57 | //防止主线程终止,导致两个线程立即退出 58 | TimeUnit.SECONDS.sleep(10); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/java_thread/basic/JoinThread.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.java_thread.basic; 2 | 3 | import java.util.concurrent.TimeUnit; 4 | 5 | /** 6 | * Thread.join() 7 | * 8 | * @author:chenssy 9 | * @date : 2016/8/10 8:54 10 | */ 11 | public class JoinThread { 12 | static class Domino implements Runnable{ 13 | private Thread thread; 14 | 15 | Domino(Thread thread){ 16 | this.thread = thread; 17 | } 18 | 19 | @Override 20 | public void run() { 21 | try { 22 | thread.join(); 23 | } catch (InterruptedException e) { 24 | e.printStackTrace(); 25 | } 26 | System.out.println(Thread.currentThread().getName() + " terminate"); 27 | } 28 | } 29 | 30 | public static void main(String[] args) throws InterruptedException { 31 | Thread previous = Thread.currentThread(); 32 | 33 | for(int i = 0 ; i < 10 ; i++){ 34 | Thread thread = new Thread(new Domino(previous),String.valueOf(i)); 35 | thread.start(); 36 | 37 | previous = thread; 38 | } 39 | 40 | TimeUnit.SECONDS.sleep(5); 41 | System.out.println(Thread.currentThread().getName() + " terminate"); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/java_thread/basic/MultiThread.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.java_thread.basic; 2 | 3 | import java.lang.management.ManagementFactory; 4 | import java.lang.management.ThreadInfo; 5 | import java.lang.management.ThreadMXBean; 6 | 7 | /** 8 | * java线程管理
9 | * ThreadMXBean : Java 虚拟机线程系统的管理接口
10 | * ThreadInfo : 线程信息 11 | * 12 | * @author:chenssy 13 | * @date : 2016/8/8 8:42 14 | */ 15 | public class MultiThread { 16 | public static void main(String[] args){ 17 | //获取java线程管理的Bean 18 | ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); 19 | //不需要获取同步的monitor和synchronizer信息,仅获取线程和线程的堆栈信息 20 | ThreadInfo[] threadInfos = threadMXBean.dumpAllThreads(false,false); 21 | 22 | for(ThreadInfo info : threadInfos){ 23 | System.out.println("[" + info.getThreadId() + "] :" + info.getThreadName()); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/java_thread/basic/ShutDownThread.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.java_thread.basic; 2 | 3 | import com.sun.java.accessibility.util.TopLevelWindowListener; 4 | import com.sun.xml.internal.ws.util.Pool; 5 | 6 | import java.util.concurrent.TimeUnit; 7 | 8 | /** 9 | * 安全有效地终止线程 10 | * 11 | * @author:chenssy 12 | * @date : 2016/8/16 8:57 13 | */ 14 | public class ShutDownThread { 15 | static class Runner implements Runnable{ 16 | private long i ; 17 | private volatile boolean on = true; 18 | @Override 19 | public void run() { 20 | while(on && !Thread.currentThread().isInterrupted()){ 21 | i++; 22 | } 23 | System.out.println("Count i = " + i); 24 | } 25 | 26 | public void cancle(){ 27 | on = false; 28 | } 29 | } 30 | 31 | public static void main(String[] args) throws InterruptedException { 32 | Runner one = new Runner(); 33 | Thread countThread = new Thread(one,"CountThread"); 34 | countThread.start(); 35 | 36 | //休眠1秒,main线程对CountThread进行中断,使CountThread能够感知中断而结束 37 | TimeUnit.SECONDS.sleep(1); 38 | countThread.interrupt(); 39 | 40 | Runner two = new Runner(); 41 | countThread = new Thread(two,"CountThread"); 42 | countThread.start(); 43 | 44 | //休眠1秒,main线程对Ruuner two 进行取消,使得CountThread能够感知on为false而结束 45 | TimeUnit.SECONDS.sleep(1); 46 | two.cancle(); 47 | } 48 | 49 | 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/java_thread/basic/ThreadState.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.java_thread.basic; 2 | 3 | import java.util.concurrent.TimeUnit; 4 | 5 | /** 6 | * 深入理解线程状态 7 | * 8 | * @author:chenssy 9 | * @date : 2016/8/8 9:02 10 | */ 11 | public class ThreadState { 12 | 13 | 14 | public static void main(String args[]){ 15 | new Thread(new TimeWaiting(),"TimeWaitingTread").start(); 16 | new Thread(new Waiting(),"WaitingThread").start(); 17 | new Thread(new Blocked(),"BlockedThread-1").start(); 18 | new Thread(new Blocked(),"BlockedThread-2").start(); 19 | } 20 | 21 | static class TimeWaiting implements Runnable{ 22 | @Override 23 | public void run() { 24 | while(true){ 25 | SleepUtils.second(100); 26 | } 27 | } 28 | } 29 | 30 | static class Waiting implements Runnable{ 31 | @Override 32 | public void run() { 33 | while(true){ 34 | synchronized (Waiting.class){ 35 | try { 36 | Waiting.class.wait(); 37 | } catch (InterruptedException e) { 38 | e.printStackTrace(); 39 | } 40 | } 41 | } 42 | } 43 | } 44 | 45 | static class Blocked implements Runnable{ 46 | @Override 47 | public void run() { 48 | synchronized (Blocked.class){ 49 | while (true){ 50 | SleepUtils.second(100); 51 | } 52 | } 53 | } 54 | } 55 | 56 | static class SleepUtils{ 57 | static final void second(long seconds){ 58 | try { 59 | TimeUnit.SECONDS.sleep(seconds); 60 | } catch (InterruptedException e) { 61 | e.printStackTrace(); 62 | } 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/java_thread/basic/WaitAndNotify.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.java_thread.basic; 2 | 3 | import java.text.SimpleDateFormat; 4 | import java.util.Date; 5 | import java.util.concurrent.TimeUnit; 6 | 7 | /** 8 | * ${todo} 9 | * 10 | * @author:chenssy 11 | * @date : 2016/8/9 13:00 12 | */ 13 | public class WaitAndNotify { 14 | static boolean flag = true; 15 | static Object lock = new Object(); 16 | static class WaitThread implements Runnable{ 17 | @Override 18 | public void run() { 19 | synchronized (lock){ 20 | while (flag){ 21 | System.out.println(Thread.currentThread() + "flag is true . wait @ " + new SimpleDateFormat("HH:mm:ss").format(new Date())); 22 | try { 23 | lock.wait(); 24 | } catch (InterruptedException e) { 25 | e.printStackTrace(); 26 | } 27 | } 28 | System.out.println(Thread.currentThread() + "flag is false . wait @ " + new SimpleDateFormat("HH:mm:ss").format(new Date())); 29 | } 30 | } 31 | } 32 | 33 | static class NotifyThread implements Runnable{ 34 | @Override 35 | public void run() { 36 | synchronized (lock){ 37 | System.out.println(Thread.currentThread() + "hold lock. notify @ " + new SimpleDateFormat("HH:mm:ss").format(new Date())); 38 | lock.notifyAll(); 39 | flag = false; 40 | 41 | try { 42 | TimeUnit.SECONDS.sleep(5); 43 | } catch (InterruptedException e) { 44 | e.printStackTrace(); 45 | } 46 | } 47 | 48 | synchronized (lock){ 49 | System.out.println(Thread.currentThread() + "hold lock again . notify @ " + new SimpleDateFormat("HH:mm:ss").format(new Date())); 50 | try { 51 | TimeUnit.SECONDS.sleep(5); 52 | } catch (InterruptedException e) { 53 | e.printStackTrace(); 54 | } 55 | } 56 | } 57 | } 58 | 59 | public static void main(String[] args){ 60 | Thread waitThread = new Thread(new WaitThread(),"waitThread"); 61 | waitThread.start(); 62 | 63 | Thread notifyThread = new Thread(new NotifyThread(),"notifyThread"); 64 | notifyThread.start(); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/java_thread/basic/synchronize/Account.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.java_thread.basic.synchronize; 2 | 3 | 4 | public class Account { 5 | private double balance = 0.0f; 6 | 7 | public double getBalance() { 8 | return balance; 9 | } 10 | 11 | public void setBalance(double balance) { 12 | this.balance = balance; 13 | } 14 | 15 | public synchronized void addAmount(double amount){ 16 | double tmp = balance; 17 | try { 18 | Thread.sleep(10); 19 | } catch (InterruptedException e) { 20 | e.printStackTrace(); 21 | }; 22 | tmp += amount; 23 | balance = tmp; 24 | } 25 | 26 | public synchronized void SubtractAmount(double amount){ 27 | double tmp = balance; 28 | try { 29 | Thread.sleep(10); 30 | } catch (InterruptedException e) { 31 | e.printStackTrace(); 32 | }; 33 | tmp -= amount; 34 | balance = tmp; 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/java_thread/basic/synchronize/Bank.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.java_thread.basic.synchronize; 2 | 3 | public class Bank implements Runnable{ 4 | 5 | private Account account; 6 | 7 | public Bank(Account account){ 8 | this.account = account; 9 | } 10 | 11 | @Override 12 | public void run() { 13 | for(int i = 0 ; i < 100 ; i++){ 14 | account.SubtractAmount((double)1000); 15 | System.out.println("Company subtract account : 1000 , the balance : " + account.getBalance() ); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/java_thread/basic/synchronize/Company.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.java_thread.basic.synchronize; 2 | 3 | public class Company implements Runnable{ 4 | 5 | private Account account; 6 | 7 | public Company(Account account){ 8 | this.account = account; 9 | } 10 | 11 | @Override 12 | public void run() { 13 | for(int i = 0 ; i < 99 ; i++){ 14 | account.addAmount(1000); 15 | System.out.println("Company add account : 1000 , the balance : " + account.getBalance() ); 16 | } 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/java_thread/model/GuardedSuspension/ClientThread.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.java_thread.model.GuardedSuspension; 2 | 3 | /** 4 | * @Author: chenssy 5 | * @Date: 2016/10/26 22:30 6 | */ 7 | public class ClientThread extends Thread{ 8 | private RequestQueue requestQueue; 9 | 10 | public ClientThread(RequestQueue requestQueue ,String name){ 11 | super(name); 12 | this.requestQueue = requestQueue; 13 | } 14 | 15 | @Override 16 | public void run() { 17 | for(int i = 0 ; i < 10 ; i++){ 18 | Request request = new Request("RequestId:" + i + "ThreadName:" + Thread.currentThread().getName()); 19 | System.out.println(Thread.currentThread().getName() + " request " + request); 20 | 21 | requestQueue.addRequest(request); //提交请求 22 | 23 | try { 24 | Thread.sleep(100); //客户端请求速度快于服务端处理速度 25 | } catch (InterruptedException e) { 26 | e.printStackTrace(); 27 | } 28 | System.out.println("ClientThread name is "+Thread.currentThread().getName()); 29 | } 30 | 31 | System.out.println(Thread.currentThread().getName() + "request end"); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/java_thread/model/GuardedSuspension/Request.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.java_thread.model.GuardedSuspension; 2 | 3 | /** 4 | * @Author: chenssy 5 | * @Date: 2016/10/26 22:13 6 | */ 7 | public class Request { 8 | private String name; 9 | 10 | public Request(String name){ 11 | this.name = name; 12 | } 13 | 14 | @Override 15 | public String toString() { 16 | return "[Request " + name + "]"; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/java_thread/model/GuardedSuspension/RequestQueue.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.java_thread.model.GuardedSuspension; 2 | 3 | import java.util.LinkedList; 4 | import java.util.List; 5 | 6 | /** 7 | * 维护Request请求信息 8 | * 9 | * @Author: chenssy 10 | * @Date: 2016/10/26 22:23 11 | */ 12 | public class RequestQueue { 13 | private LinkedList queue = new LinkedList(); 14 | 15 | public synchronized Request getRequest(){ 16 | while(queue.size() == 0){ 17 | try{ 18 | wait(); //等待,直到有Request 19 | }catch(InterruptedException e){ 20 | 21 | } 22 | } 23 | 24 | return (Request) queue.remove(); 25 | } 26 | 27 | public synchronized void addRequest(Request request){ 28 | queue.add(request); 29 | notifyAll(); //唤醒getRequest方法 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/java_thread/model/GuardedSuspension/ServerThread.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.java_thread.model.GuardedSuspension; 2 | 3 | /** 4 | * @Author: chenssy 5 | * @Date: 2016/10/26 22:27 6 | */ 7 | public class ServerThread extends Thread{ 8 | private RequestQueue requestQueue; 9 | 10 | public ServerThread(RequestQueue requestQueue,String name){ 11 | super(name); 12 | this.requestQueue = requestQueue; 13 | } 14 | 15 | @Override 16 | public void run() { 17 | while(true){ 18 | final Request request = requestQueue.getRequest(); 19 | 20 | try { 21 | Thread.sleep(1000); 22 | } catch (InterruptedException e) { 23 | 24 | } 25 | System.out.println(Thread.currentThread().getName() + " handles " + request); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/java_thread/model/GuardedSuspension/Test.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.java_thread.model.GuardedSuspension; 2 | 3 | /** 4 | * @Author: chenssy 5 | * @Date: 2016/10/26 22:35 6 | */ 7 | public class Test { 8 | public static void main(String[] args){ 9 | RequestQueue requestQueue = new RequestQueue(); 10 | 11 | //开启服务端进程 12 | for(int i = 0 ; i < 10 ; i++){ 13 | new ServerThread(requestQueue,"ServerThread_" + i).start(); 14 | } 15 | 16 | //开启客户端进程 17 | for(int i = 0 ; i < 10 ; i++){ 18 | new ClientThread(requestQueue,"ClientThread_" + i).start(); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/java_thread/model/MasterWorker/Master.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.java_thread.model.MasterWorker; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | import java.util.Queue; 6 | import java.util.concurrent.ConcurrentHashMap; 7 | import java.util.concurrent.ConcurrentLinkedDeque; 8 | 9 | /** 10 | * @Author: chenssy 11 | * @Date: 2016/10/26 21:03 12 | */ 13 | public class Master { 14 | //任务队列 15 | protected Queue workQueue = new ConcurrentLinkedDeque(); 16 | //Work进程队列 17 | protected Map threadMap = new HashMap(); 18 | //子任务处理结果集 19 | protected Map resultMap = new ConcurrentHashMap(); 20 | 21 | /** 22 | * 判断任务是否结束 23 | * 24 | * @author chenssy 25 | * @date 2016-10-26 26 | * @since v1.0.0 27 | */ 28 | public boolean isComplete(){ 29 | for(Map.Entry entry : threadMap.entrySet()){ 30 | if(entry.getValue().getState() != Thread.State.TERMINATED){ 31 | return false; 32 | } 33 | } 34 | return true; 35 | } 36 | 37 | public Master(Worker worker,int countWorker){ 38 | worker.setWorkerQueue(workQueue); 39 | worker.setResultMap(resultMap); 40 | 41 | for(int i = 0 ; i < countWorker ; i++){ 42 | threadMap.put(Integer.toString(i),new Thread(worker,Integer.toString(i))); 43 | } 44 | } 45 | 46 | /** 47 | * 提交一个任务 48 | * 49 | * @author chenssy 50 | * @date 2016-10-26 51 | * @since v1.0.0 52 | */ 53 | public void submit(Object object){ 54 | workQueue.add(object); 55 | } 56 | 57 | /** 58 | * 获取结果集 59 | * 60 | * @author chenssy 61 | * @date 2016-10-26 62 | * @since v1.0.0 63 | */ 64 | public Map getResultMap(){ 65 | return resultMap; 66 | } 67 | 68 | /** 69 | * 执行子任务 70 | * 71 | * @author chenssy 72 | * @date 2016-10-26 73 | * @since v1.0.0 74 | */ 75 | public void execute(){ 76 | for (Map.Entry entery:threadMap.entrySet()){ 77 | entery.getValue().start(); 78 | } 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/java_thread/model/MasterWorker/PlusWorker.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.java_thread.model.MasterWorker; 2 | 3 | /** 4 | * @Author: chenssy 5 | * @Date: 2016/10/26 21:25 6 | */ 7 | public class PlusWorker extends Worker { 8 | @Override 9 | public Object handle(Object input) { 10 | Integer i = (Integer) input; 11 | return i * i * i; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/java_thread/model/MasterWorker/Test.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.java_thread.model.MasterWorker; 2 | 3 | import java.util.Map; 4 | import java.util.Set; 5 | 6 | /** 7 | * @Author: chenssy 8 | * @Date: 2016/10/26 21:32 9 | */ 10 | public class Test { 11 | public static void main(String[] args){ 12 | //五个进程跑 13 | Master master = new Master(new PlusWorker(),5); 14 | 15 | //提交100个子任务 16 | for(int i = 0 ; i < 100 ; i++){ 17 | master.submit(i); 18 | } 19 | 20 | master.execute(); 21 | 22 | int result = 0 ; 23 | 24 | Map resultMap = master.getResultMap(); 25 | 26 | while(resultMap.size() > 0 || !master.isComplete()){ 27 | Set keys = resultMap.keySet(); 28 | String key = null; 29 | for(String s : keys){ 30 | key = s; 31 | break; 32 | } 33 | 34 | Integer i = null; 35 | 36 | if(key != null){ 37 | i = (Integer) resultMap.get(key); 38 | } 39 | if(i != null){ 40 | result += i; 41 | } 42 | 43 | if(key != null){ 44 | resultMap.remove(key); 45 | } 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/java_thread/model/MasterWorker/Worker.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.java_thread.model.MasterWorker; 2 | 3 | import java.util.Map; 4 | import java.util.Queue; 5 | 6 | /** 7 | * @Author: chenssy 8 | * @Date: 2016/10/26 21:15 9 | */ 10 | public class Worker implements Runnable{ 11 | protected Queue workerQueue; 12 | 13 | protected Map resultMap ; 14 | 15 | public void setWorkerQueue(Queue workerQueue) { 16 | this.workerQueue = workerQueue; 17 | } 18 | 19 | public void setResultMap(Map resultMap) { 20 | this.resultMap = resultMap; 21 | } 22 | 23 | @Override 24 | public void run() { 25 | while (true){ 26 | Object input = workerQueue.poll(); 27 | if(input == null){ 28 | break; 29 | } 30 | 31 | System.out.println("子任务【" + Thread.currentThread().getName() + "】开始执行,执行对象为--" + input.toString()); 32 | Object result = handle(input); 33 | System.out.println("子任务【" + Thread.currentThread().getName() + "】执行完成,结果为:" + result.toString()); 34 | resultMap.put(Integer.toString(input.hashCode()),result); 35 | } 36 | } 37 | 38 | /** 39 | * 子任务处理逻辑,在子类中覆盖执行具体逻辑 40 | * 41 | * @author chenssy 42 | * @date 2016-10-26 43 | * @since v1.0.0 44 | */ 45 | public Object handle(Object input) { 46 | return input; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/java_thread/threadPool/custom/PThread.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.java_thread.threadPool.custom; 2 | 3 | /** 4 | * @author chenssy 5 | * @date 2016/10/31 6 | * @since v1.0.0 7 | */ 8 | public class PThread extends Thread{ 9 | //线程池 10 | private ThreadPool pool; 11 | 12 | //任务 13 | private Runnable target; 14 | 15 | private boolean isShutDown = false; 16 | private boolean isIdle = false; 17 | 18 | public PThread(Runnable target,String name,ThreadPool pool){ 19 | super(name); 20 | this.pool = pool; 21 | this.target = target; 22 | } 23 | 24 | public Runnable getTarget(){ 25 | return target; 26 | } 27 | 28 | public boolean isIdle(){ 29 | return isIdle; 30 | } 31 | 32 | public void run(){ 33 | while(!isShutDown){ 34 | isIdle = true; 35 | if(target != null){ 36 | target.run(); //运行线程 37 | } 38 | 39 | //任务结束了,到闲置状态 40 | isIdle = true; 41 | 42 | try { 43 | pool.repool(this); 44 | synchronized (this){ 45 | //线程空闲,等待任务到来 46 | wait(); 47 | } 48 | } catch (InterruptedException e) { 49 | 50 | } 51 | isIdle = false; 52 | } 53 | } 54 | 55 | public synchronized void setTarget(Runnable newTarget){ 56 | target = newTarget; 57 | //设置任务后,通知run方法,执行任务 58 | notifyAll(); 59 | } 60 | 61 | //关闭线程 62 | public synchronized void shutDown(){ 63 | isShutDown = true; 64 | notifyAll(); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/java_thread/threadPool/custom/Test.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.java_thread.threadPool.custom; 2 | 3 | /** 4 | * @author chenssy 5 | * @date 2016/10/31 6 | * @since v1.0.0 7 | */ 8 | public class Test { 9 | 10 | public static void main(String[] args){ 11 | long begin1 = System.currentTimeMillis(); 12 | for(int i = 0 ; i < 500 ; i++){ 13 | new Thread(new MyThread("no pool_"+i)).start(); 14 | } 15 | long end1 = System.currentTimeMillis(); 16 | 17 | long begin2 = System.currentTimeMillis(); 18 | for(int i = 0 ; i < 500 ; i++){ 19 | ThreadPool.getInstance().start(new MyThread("pool_"+i)); 20 | } 21 | long end2 = System.currentTimeMillis(); 22 | 23 | System.out.println("no pool times:" + (end1 - begin1)); 24 | System.out.println("pool times:" + (end2 - begin2)); 25 | } 26 | 27 | private static class MyThread implements Runnable{ 28 | String name = null; 29 | public MyThread(String name) { 30 | this.name = name; 31 | } 32 | 33 | @Override 34 | public void run() { 35 | try { 36 | Thread.sleep(100); 37 | } catch (InterruptedException e) { 38 | e.printStackTrace(); 39 | } 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/java_thread/threadPool/custom/ThreadPool.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.java_thread.threadPool.custom; 2 | 3 | import java.util.List; 4 | import java.util.Vector; 5 | 6 | /** 7 | * 自定义线程池 8 | * @author chenssy 9 | * @date 2016/10/31 21:38 10 | */ 11 | public class ThreadPool { 12 | private static ThreadPool instance = null; 13 | 14 | //空闲的线程队列 15 | private List idleThreads; 16 | 17 | private int threadCounter; 18 | private boolean isShutDown = false; 19 | 20 | private ThreadPool(){ 21 | this.idleThreads = new Vector(5); 22 | threadCounter = 0; 23 | } 24 | 25 | public int getCreatedThreadsCount(){ 26 | return threadCounter; 27 | } 28 | 29 | public synchronized static ThreadPool getInstance(){ 30 | if(instance == null){ 31 | instance = new ThreadPool(); 32 | } 33 | return instance; 34 | } 35 | 36 | //将线程加入线程池中 37 | protected synchronized void repool(PThread thread){ 38 | if(!isShutDown){ 39 | idleThreads.add(thread); 40 | }else{ 41 | thread.shutDown(); 42 | } 43 | } 44 | 45 | /** 46 | * 停止池中所有线程 47 | * 48 | * @author chenssy 49 | * @date 2016-10-31 50 | * @since v1.0.0 51 | */ 52 | public synchronized void shutDown(){ 53 | isShutDown = true; 54 | for(int i = 0 ; i < idleThreads.size() ; i++){ 55 | PThread thread = (PThread) idleThreads.get(i); 56 | thread.shutDown(); 57 | } 58 | } 59 | 60 | public synchronized void start(Runnable runnable){ 61 | PThread thread = null; 62 | //有空闲线程 直接使用 63 | if(idleThreads.size() > 0){ 64 | int lastIndex = idleThreads.size() - 1; 65 | thread = (PThread) idleThreads.get(lastIndex); 66 | 67 | idleThreads.remove(thread); 68 | 69 | //执行任务 70 | thread.setTarget(thread); 71 | }else{ //没有空闲线程,则创建新的线程 72 | threadCounter++; 73 | thread = new PThread(runnable,"PThread #" + threadCounter,this); 74 | 75 | //启动该线程 76 | thread.start(); 77 | } 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/junit/_1/Calculator.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.junit._1; 2 | 3 | public class Calculator { 4 | private static int result; // 静态变量,用于存储运行结果 5 | 6 | public void add(int n) { 7 | result = result + n; 8 | } 9 | 10 | public void substract(int n) { 11 | result = result - 1; // Bug: 正确的应该是 result =result-n 12 | } 13 | 14 | public void multiply(int n) { 15 | } // 此方法尚未写好 16 | 17 | public void divide(int n) { 18 | result = result / n; 19 | } 20 | 21 | public void square(int n) { 22 | result = n * n; 23 | } 24 | 25 | public void squareRoot(int n) { 26 | for (;;) 27 | ; // Bug : 死循环 28 | } 29 | 30 | public void clear() { // 将结果清零 31 | result = 0; 32 | } 33 | 34 | public int getResult() { 35 | return result; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/proxy/_1/Client.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.proxy._1; 2 | 3 | public class Client { 4 | public static void main(String[] args) { 5 | RealSubject realSubject = new RealSubject("chenssy"); 6 | 7 | ProxySubject proxySubject = new ProxySubject(realSubject); 8 | proxySubject.request(); 9 | } 10 | } -------------------------------------------------------------------------------- /src/main/java/com/javaCore/proxy/_1/ProxySubject.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.proxy._1; 2 | 3 | public class ProxySubject implements Subject{ 4 | 5 | private RealSubject realSubject; 6 | 7 | public ProxySubject(RealSubject realSubject){ 8 | this.realSubject = realSubject; 9 | } 10 | 11 | @Override 12 | public void request() { 13 | realSubject.request(); 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/proxy/_1/RealSubject.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.proxy._1; 2 | 3 | /** 4 | * 5 | * ��ʵ��ɫ�������ɫ���������ʵ��������������Ҫ���õĶ��� 6 | * 7 | * @Project:JavaCore 8 | * @file:RealSubject.java 9 | * 10 | * @Author:chenssy 11 | * @email:chenssy995812509@163.com 12 | * @url : http://cmsblogs.com 13 | * @qq : 122448894 14 | * 15 | * @data:2016��1��6�� 16 | */ 17 | public class RealSubject implements Subject{ 18 | 19 | private String name; 20 | 21 | public RealSubject(String name){ 22 | this.name = name; 23 | } 24 | 25 | @Override 26 | public void request() { 27 | System.out.println(name + "----��ʵ��ɫ......"); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/proxy/_1/Subject.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.proxy._1; 2 | 3 | /** 4 | * �����ɫ��������ʵ����ʹ������Ĺ�ͬ�ӿ� 5 | * 6 | * @Project:JavaCore 7 | * @file:Subject.java 8 | * 9 | * @Author:chenssy 10 | * @email:chenssy995812509@163.com 11 | * @url : http://cmsblogs.com 12 | * @qq : 122448894 13 | * 14 | * @data:2016��1��6�� 15 | */ 16 | public interface Subject { 17 | void request(); 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/proxy/_2/Client.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.proxy._2; 2 | 3 | import java.lang.reflect.InvocationHandler; 4 | import java.lang.reflect.Proxy; 5 | 6 | public class Client { 7 | public static void main(String[] args) { 8 | RealSubject realSubject = new RealSubject("chenssy"); 9 | InvocationHandler ds = new DynamicSubject(realSubject); 10 | 11 | //���ɴ����� 12 | Subject subject = (Subject) Proxy.newProxyInstance(realSubject.getClass().getClassLoader(),realSubject.getClass().getInterfaces(),ds); 13 | subject.request(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/proxy/_2/DynamicSubject.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.proxy._2; 2 | 3 | import java.lang.reflect.InvocationHandler; 4 | import java.lang.reflect.Method; 5 | 6 | /** 7 | * �������� 8 | * 9 | * @Project:JavaCore 10 | * @file:DynamicSubject.java 11 | * 12 | * @Author:chenssy 13 | * @email:chenssy995812509@163.com 14 | * @url : http://cmsblogs.com 15 | * @qq : 122448894 16 | * 17 | * @data:2016��1��6�� 18 | */ 19 | public class DynamicSubject implements InvocationHandler{ 20 | 21 | private Object object; 22 | 23 | public DynamicSubject(Object object){ 24 | this.object = object; 25 | } 26 | 27 | @Override 28 | public Object invoke(Object proxy, Method method, Object[] args) 29 | throws Throwable { 30 | System.out.println("���ô�����֮ǰ��ִ�еķ���...." + method); 31 | 32 | method.invoke(object, args); 33 | 34 | System.out.println("���ô�����֮��ִ�еķ���...." + method); 35 | 36 | return null; 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/proxy/_2/RealSubject.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.proxy._2; 2 | 3 | /** 4 | * 5 | * ��ʵ��ɫ�������ɫ���������ʵ��������������Ҫ���õĶ��� 6 | * 7 | * @Project:JavaCore 8 | * @file:RealSubject.java 9 | * 10 | * @Author:chenssy 11 | * @email:chenssy995812509@163.com 12 | * @url : http://cmsblogs.com 13 | * @qq : 122448894 14 | * 15 | * @data:2016��1��6�� 16 | */ 17 | public class RealSubject implements Subject{ 18 | 19 | private String name; 20 | 21 | public RealSubject(String name){ 22 | this.name = name; 23 | } 24 | 25 | @Override 26 | public void request() { 27 | System.out.println(name + "----��ʵ��ɫ......"); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/javaCore/proxy/_2/Subject.java: -------------------------------------------------------------------------------- 1 | package com.javaCore.proxy._2; 2 | 3 | public interface Subject { 4 | void request(); 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/com/redis/JRedisPoolUtils.java: -------------------------------------------------------------------------------- 1 | package com.redis; 2 | 3 | import redis.clients.jedis.Jedis; 4 | import redis.clients.jedis.JedisPool; 5 | import redis.clients.jedis.JedisPoolConfig; 6 | 7 | /** 8 | * Redis的连接池 9 | * 10 | * @author:chenming 11 | * @date : 2016/10/31 8:56 12 | */ 13 | public class JRedisPoolUtils { 14 | private final static String REDIS_IP = "localhost"; 15 | 16 | //可用连接实例的最大数目,默认值为8; 17 | //如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。 18 | private static int MAX_ACTIVE = 1024; 19 | 20 | //控制一个pool最多有多少个状态为idle(空闲的)的jedis实例,默认值也是8。 21 | private static int MAX_IDLE = 200; 22 | 23 | //等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出JedisConnectionException; 24 | private static int MAX_WAIT = 10000; 25 | 26 | private static int TIMEOUT = 10000; 27 | 28 | //在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的; 29 | private static boolean TEST_ON_BORROW = true; 30 | 31 | private static JedisPool jedisPool = null; 32 | 33 | /** 34 | * 初始化连接池 35 | */ 36 | static { 37 | JedisPoolConfig config = new JedisPoolConfig(); 38 | config.setMaxActive(MAX_ACTIVE); 39 | config.setMaxIdle(MAX_IDLE); 40 | config.setMaxWait(MAX_WAIT); 41 | config.setTestOnBorrow(TEST_ON_BORROW); 42 | jedisPool = new JedisPool(config,REDIS_IP); 43 | } 44 | 45 | /** 46 | * 获取Redis实例 47 | * 48 | * @author chenming 49 | * @date 2016-11-06 50 | * @since v1.0.0 51 | */ 52 | public synchronized static Jedis getJedis(){ 53 | if(jedisPool != null){ 54 | return jedisPool.getResource(); 55 | }else{ 56 | return null; 57 | } 58 | } 59 | 60 | /** 61 | * 释放jedis资源 62 | * 63 | * @author chenming 64 | * @date 2016-11-06 65 | * @since v1.0.0 66 | */ 67 | public static void returnJedis(final Jedis jedis){ 68 | if(jedisPool != null){ 69 | jedisPool.returnResource(jedis); 70 | } 71 | } 72 | 73 | } 74 | -------------------------------------------------------------------------------- /src/main/java/com/redis/JRedisTest.java: -------------------------------------------------------------------------------- 1 | package com.redis; 2 | 3 | import org.junit.Before; 4 | import org.junit.Test; 5 | import redis.clients.jedis.Jedis; 6 | 7 | import java.util.HashMap; 8 | import java.util.List; 9 | import java.util.Map; 10 | 11 | /** 12 | * @Author: chenssy 13 | * @Date: 2016/10/30 9:41 14 | */ 15 | public class JRedisTest { 16 | private Jedis jedis = null; 17 | 18 | @Before 19 | public void setUp(){ 20 | //连接redis服务器 21 | jedis = new Jedis("localhost"); 22 | } 23 | 24 | /** 25 | * String Test 26 | * 27 | * @author chenssy 28 | * @date 2016-10-30 29 | * @since v1.0.0 30 | */ 31 | @Test 32 | public void stringTest(){ 33 | jedis.set("name", "chenssy"); 34 | System.out.println(jedis.get("name")); 35 | 36 | jedis.append("name","_cmblogs.com"); 37 | System.out.println(jedis.get("name")); 38 | 39 | jedis.del("name"); 40 | System.out.println(jedis.get("name")); 41 | 42 | jedis.mset("name","chenssy","blog","cmsblogs"); 43 | System.out.println(jedis.get("name") + "--" + jedis.get("blog")); 44 | } 45 | 46 | /** 47 | * Map test 48 | * 49 | * @author chenssy 50 | * @date 2016-10-30 51 | * @since v1.0.0 52 | */ 53 | @Test 54 | public void mapTest(){ 55 | Map user = new HashMap(); 56 | user.put("name","chenssy"); 57 | user.put("sex","boy"); //O(∩_∩)O~ 58 | user.put("github","chenssy89"); 59 | user.put("QQ","122448894"); 60 | 61 | jedis.hmset("user" ,user); 62 | 63 | //第一个参数是存入redis中map对象的key,后面跟的是放入map中的对象的key,后面的key可以跟多个,是可变参数 64 | List list = jedis.hmget("user","name","sex","github","QQ"); 65 | System.out.println(list); 66 | 67 | jedis.hdel("user","QQ"); 68 | System.out.println(jedis.hmget("user", "name", "QQ")); 69 | System.out.println("user 中元素的个数:" + jedis.hlen("user")); 70 | System.out.println("jedis 中是否存在user:" + jedis.exists("user")); 71 | System.out.println("user 中的key:" + jedis.hkeys("user")); 72 | System.out.println("user 中的key:"+jedis.hvals("user")); 73 | } 74 | 75 | /** 76 | * List Test 77 | * 78 | * @author chenssy 79 | * @date 2016-10-30 80 | * @since v1.0.0 81 | */ 82 | @Test 83 | public void listTest(){ 84 | jedis.del("list"); 85 | 86 | jedis.lpush("list","chenssy"); 87 | jedis.lpush("list","boy"); 88 | jedis.lpush("list","chenss89"); 89 | jedis.lpush("list","122448894"); 90 | 91 | /* 92 | *再取出所有数据jedis.lrange是按范围取出, 93 | *第一个是key,第二个是起始位置,第三个是结束位置,jedis.llen获取长度 -1表示取得所有 94 | */ 95 | 96 | System.out.println(jedis.lrange("list",0,-1)); 97 | System.out.println(jedis.lpop("list")); 98 | System.out.println(jedis.lrange("list",0,-1)); 99 | } 100 | 101 | /** 102 | * Set 集合Test 103 | * 104 | * @author chenssy 105 | * @date 2016-10-30 106 | * @since v1.0.0 107 | */ 108 | @Test 109 | public void setTest(){ 110 | jedis.sadd("set","chenssy"); 111 | jedis.sadd("set","boy"); 112 | jedis.sadd("set","chenssy89"); 113 | jedis.sadd("set","122448894"); 114 | jedis.sadd("set","chenssy"); 115 | 116 | System.out.println(jedis.smembers("set")); 117 | System.out.println(jedis.sismember("set", "boy")); 118 | System.out.println(jedis.srandmember("set")); 119 | System.out.println(jedis.scard("set")); 120 | } 121 | 122 | /** 123 | * 排序 124 | * 125 | * @author chenssy 126 | * @date 2016-10-30 127 | * @since v1.0.0 128 | */ 129 | @Test 130 | public void sortTest(){ 131 | jedis.del("sort"); 132 | 133 | jedis.rpush("sort","8"); 134 | jedis.rpush("sort","7"); 135 | jedis.rpush("sort","9"); 136 | jedis.rpush("sort","6"); 137 | jedis.rpush("sort","4"); 138 | jedis.rpush("sort","5"); 139 | 140 | System.out.println(jedis.lrange("sort",0,-1)); 141 | System.out.println(jedis.sort("sort")); 142 | System.out.println(jedis.lrange("sort",0,-1)); 143 | } 144 | 145 | /** 146 | * 连接池test 147 | * 148 | * @author chenming 149 | * @date 2016-11-06 150 | * @since v1.0.0 151 | */ 152 | @Test 153 | public void redisPoolTest(){ 154 | JRedisPoolUtils.getJedis().set("pool","chenssy-redis-pool"); 155 | System.out.println(JRedisPoolUtils.getJedis().get("pool")); 156 | } 157 | } 158 | -------------------------------------------------------------------------------- /src/main/java/com/redis/RedisInvokeTest.java: -------------------------------------------------------------------------------- 1 | package com.redis; 2 | 3 | import org.junit.Test; 4 | import redis.clients.jedis.*; 5 | 6 | import java.util.Arrays; 7 | import java.util.List; 8 | 9 | /** 10 | * Redis 调用方式 11 | * 12 | * @author chenming 13 | * @date 2016/11/6 16:12 14 | */ 15 | public class RedisInvokeTest { 16 | 17 | /** 18 | * 普通同步方式 19 | * 20 | * @author chenming 21 | * @date 2016-11-06 22 | * @since v1.0.0 23 | */ 24 | @Test 25 | public void normalTest() { 26 | Jedis jedis = new Jedis("localhost"); 27 | 28 | long begin = System.currentTimeMillis(); 29 | 30 | for (int i = 0; i < 1000; i++) { 31 | //set之后都可以返回结果,标记是否成功 32 | System.out.println(i + "---" + jedis.set("n_" + i, "n_" + i)); 33 | } 34 | 35 | long end = System.currentTimeMillis(); 36 | 37 | System.out.println("normal Set:" + (end - begin)); 38 | 39 | jedis.disconnect(); 40 | } 41 | 42 | /** 43 | * 事务方式调用 44 | * 45 | * 主要目的是保障,一个client发起的事务中的命令可以连续的执行,而中间不会插入其他client的命令 46 | * 47 | * @author chenming 48 | * @date 2016-11-06 49 | * @since v1.0.0 50 | */ 51 | @Test 52 | public void transTest() { 53 | Jedis jedis = new Jedis("localhost"); 54 | 55 | long begin = System.currentTimeMillis(); 56 | Transaction transaction = jedis.multi(); 57 | for (int i = 0; i < 1000; i++) { 58 | transaction.set("t_" + i, "t_" + i); 59 | } 60 | List result = transaction.exec(); 61 | 62 | long end = System.currentTimeMillis(); 63 | 64 | System.out.println("Transaction Set:" + (end - begin)); 65 | jedis.disconnect(); 66 | System.out.println(result); 67 | } 68 | 69 | /** 70 | * 管道方式调用 71 | * 采用异步方式,一次发送多个指令,不同步等待其返回结果 72 | * 73 | * @author chenming 74 | * @date 2016-11-06 75 | * @since v1.0.0 76 | */ 77 | @Test 78 | public void PipelinedTest() { 79 | Jedis jedis = new Jedis("localhost"); 80 | 81 | long begin = System.currentTimeMillis(); 82 | Pipeline pipeline = jedis.pipelined(); 83 | for (int i = 0; i < 1000; i++) { 84 | pipeline.set("p_" + i, "p_" + i); 85 | } 86 | List result = pipeline.syncAndReturnAll(); 87 | 88 | long end = System.currentTimeMillis(); 89 | 90 | System.out.println("pipeline Set:" + (end - begin)); 91 | jedis.disconnect(); 92 | System.out.println(result); 93 | } 94 | 95 | /** 96 | * 分布式直连同步调用/异步改为ShardedJedisPipeline 即可 97 | * 98 | * @author chenming 99 | * @date 2016-10-31 100 | * @since v1.0.0 101 | */ 102 | @Test 103 | public void shardNormalTest(){ 104 | List shards = Arrays.asList( 105 | new JedisShardInfo("localhost",6379), 106 | new JedisShardInfo("localhost",6380) 107 | ); 108 | 109 | ShardedJedis sharding = new ShardedJedis(shards); 110 | 111 | long start = System.currentTimeMillis(); 112 | for (int i = 0; i < 1000; i++) { 113 | String result = sharding.set("shardNormal " + i, "sn" + i); 114 | } 115 | 116 | long end = System.currentTimeMillis(); 117 | System.out.println("shardNormal SET: " + (end - start)); 118 | 119 | sharding.disconnect(); 120 | } 121 | 122 | /** 123 | * 分布式连接池异步调用 124 | * 125 | * @author chenming 126 | * @date 2016-10-31 127 | * @since v1.0.0 128 | */ 129 | @Test 130 | public void shardPipelinedPoolTest(){ 131 | List shards = Arrays.asList( 132 | new JedisShardInfo("localhost",6379), 133 | new JedisShardInfo("localhost",6380)); 134 | 135 | ShardedJedisPool pool = new ShardedJedisPool(new JedisPoolConfig(),shards); 136 | 137 | ShardedJedis one = pool.getResource(); 138 | ShardedJedisPipeline pipeline = one.pipelined(); 139 | 140 | long start = System.currentTimeMillis(); 141 | for (int i = 0; i < 1000; i++) { 142 | pipeline.set("shardPipelinedPool" + i, "n" + i); 143 | } 144 | List results = pipeline.syncAndReturnAll(); 145 | long end = System.currentTimeMillis(); 146 | 147 | pool.returnResource(one); 148 | System.out.println("shardPipelinedPool SET: " + (end - start)); 149 | pool.destroy(); 150 | } 151 | } 152 | -------------------------------------------------------------------------------- /src/main/java/com/redis/Test.java: -------------------------------------------------------------------------------- 1 | package com.redis; 2 | 3 | public class Test { 4 | } 5 | -------------------------------------------------------------------------------- /src/main/resources/rebel.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /src/test/Test.java: -------------------------------------------------------------------------------- 1 | package test; 2 | 3 | import java.util.concurrent.CopyOnWriteArrayList; 4 | 5 | public class Test { 6 | 7 | public static void main(String[] args) { 8 | CopyOnWriteArrayList c = new CopyOnWriteArrayList(); 9 | c.get(1); 10 | } 11 | 12 | } 13 | --------------------------------------------------------------------------------