Java中的多线程竞争与CountDownLatch的应用

线程间的竞争叫做Racing,正如这篇文章的图片一样,不同的线程好比在高速赛道上行驶的F1方程式赛车,当赛车在各自的赛道上互不影响各自行驶时,可以相安无事。但这是一场比赛,既然是比赛,必然有并线、超车的行为,此时两辆赛车很可能会挤到赛道中公共的部分,如果此时两车速度相差不多,而且距离差距不大,就极有可能发生可怕的事故。
在计算机世界里,不同的线程运行的程序就好比不同赛道上的赛车。如果各个线程相互独立,完全没有关系,不会相互影响。但实际情况往往没有这么简单,线程可能会共同访问某个共享资源,并操作这些共享资源,如果程序逻辑依赖于这些资源,那么不同线程执行的先后次序就很有可能会影响到程序的执行结果。如果我们不对线程间的访问加以协调和控制,就可能导致错误的输出。
下面这个例子里,我想展示一下线程竞争的情况:
package net.bluedash.countdownlatch;import java.io.IOException;import java.net.ServerSocket;import java.net.Socket;public class SampleServerWithRacingProblem {private boolean running = true;private ServerSocket socket;public SampleServerWithRacingProblem() throws IOException {init();}private void init() throws IOException {socket = new ServerSocket(8080);}public void accept() {while (running) {try {Socket connection = socket.accept();connection.getOutputStream().write(". ".getBytes());connection.getOutputStream().flush();connection.close();} catch (IOException e) {System.out.print("\nC");return;}}System.out.print("\nG");}public void close() throws IOException, InterruptedException {running = false;socket.close();}package net.bluedash.countdownlatch;public class ServerWorker implements Runnable {private SampleServerWithRacingProblem server;public ServerWorker(SampleServerWithRacingProblem server) {this.server = server;}@Overridepublic void run() {System.out.print("A");server.accept();}}package net.bluedash.countdownlatch;import java.io.BufferedReader;import java.io.InputStreamReader;import java.net.Socket;public class ClientWorker implements Runnable {@Overridepublic void run() {try {while (true) {Thread.sleep(100); // 防止客户端请求太快,消耗大量系统资源Socket socket = new Socket("127.0.0.1", 8080);BufferedReader rd = new BufferedReader(new InputStreamReader(socket.getInputStream()));String line;while ((line = rd.readLine()) != null) {System.out.print(line);}socket.close();}} catch (Exception ignore) {}}}package net.bluedash.countdownlatch;import java.io.IOException;public class UseSampleServer {public static void main(String[] args) throws IOException,InterruptedException {SampleServerWithRacingProblem server = new SampleServerWithRacingProblem();ServerWorker serverWorker = new ServerWorker(server);Thread serverThread = new Thread(serverWorker);serverThread.start();// 开启5个客户端连接for (int i = 0; i < 5; i++) {ClientWorker clientWorker = new ClientWorker();Thread clientThread = new Thread(clientWorker);clientThread.start();}// 给客户端时间5秒钟时间去跑起来,防止服务器过早地关闭Thread.currentThread().sleep(5000);server.close();System.out.print("\nQ");}}A. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . QC
package net.bluedash.countdownlatch;import java.io.IOException;import java.net.ServerSocket;import java.net.Socket;import java.util.concurrent.CountDownLatch;public class SampleServerWithoutRacingProblem {private boolean running = true;private ServerSocket socket;private CountDownLatch lock = new CountDownLatch(1);public SampleServerWithoutRacingProblem() throws IOException {init();}private void init() throws IOException {socket = new ServerSocket(8080);}public void accept() {while (running) {try {Socket connection = socket.accept();connection.getOutputStream().write(". ".getBytes());connection.getOutputStream().flush();connection.close();} catch (IOException e) {System.out.print("\nC");return;}}lock.countDown();System.out.print("\nG");}public void close() throws IOException, InterruptedException {running = false;lock.await();socket.close();}}private CountDownLatch lock = new CountDownLatch(1);
lock.countDown();
public void close() throws IOException, InterruptedException {running = false;lock.await();socket.close();}A. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . GQ.
git clone git://github.com/liweinan/try-countdownlatch.git
mvn install
mvn exec:java -Dexec.main-Dexec.args='WithProblem'
mvn exec:java -Dexec.main-Dexec.args='WithoutProblem'