List of usage examples for java.lang Thread Thread
public Thread(String name)
From source file:fr.tpt.s3.mcdag.generator.MainGenerator.java
/** * Main method for the generator: it launches a given number of threads with the parameters * given/*from www . jav a2 s . com*/ * @param args */ public static void main(String[] args) { /* ============================ Command line ================= */ Options options = new Options(); Option o_hi = new Option("mu", "max_utilization", true, "Upper bound utilization"); o_hi.setRequired(true); options.addOption(o_hi); Option o_tasks = new Option("nt", "nb_tasks", true, "Number of tasks for the system"); o_tasks.setRequired(true); options.addOption(o_tasks); Option o_eprob = new Option("e", "eprobability", true, "Probability of edges"); o_eprob.setRequired(true); options.addOption(o_eprob); Option o_levels = new Option("l", "levels", true, "Number of criticality levels"); o_levels.setRequired(true); options.addOption(o_levels); Option o_para = new Option("p", "parallelism", true, "Max parallelism for the DAGs"); o_para.setRequired(true); options.addOption(o_para); Option o_nbdags = new Option("nd", "num_dags", true, "Number of DAGs"); o_nbdags.setRequired(true); options.addOption(o_nbdags); Option o_nbfiles = new Option("nf", "num_files", true, "Number of files"); o_nbfiles.setRequired(true); options.addOption(o_nbfiles); Option o_rfactor = new Option("rf", "reduc_factor", true, "Reduction factor for criticality modes"); o_rfactor.setRequired(false); options.addOption(o_rfactor); Option o_out = new Option("o", "output", true, "Output file for the DAG"); o_out.setRequired(true); options.addOption(o_out); Option graphOpt = new Option("g", "graphviz", false, "Generate a graphviz DOT file"); graphOpt.setRequired(false); options.addOption(graphOpt); Option debugOpt = new Option("d", "debug", false, "Enabling debug"); debugOpt.setRequired(false); options.addOption(debugOpt); Option jobsOpt = new Option("j", "jobs", true, "Number of jobs"); jobsOpt.setRequired(false); options.addOption(jobsOpt); CommandLineParser parser = new DefaultParser(); HelpFormatter formatter = new HelpFormatter(); CommandLine cmd; try { cmd = parser.parse(options, args); } catch (ParseException e) { System.out.println(e.getMessage()); formatter.printHelp("DAG Generator", options); System.exit(1); return; } double maxU = Double.parseDouble(cmd.getOptionValue("max_utilization")); int edgeProb = Integer.parseInt(cmd.getOptionValue("eprobability")); int levels = Integer.parseInt(cmd.getOptionValue("levels")); int nbDags = Integer.parseInt(cmd.getOptionValue("num_dags")); int nbFiles = Integer.parseInt(cmd.getOptionValue("num_files")); int para = Integer.parseInt(cmd.getOptionValue("parallelism")); int nbTasks = Integer.parseInt(cmd.getOptionValue("nb_tasks")); boolean graph = cmd.hasOption("graphviz"); boolean debug = cmd.hasOption("debug"); String output = cmd.getOptionValue("output"); int nbJobs = 1; if (cmd.hasOption("jobs")) nbJobs = Integer.parseInt(cmd.getOptionValue("jobs")); double rfactor = 2.0; if (cmd.hasOption("reduc_factor")) rfactor = Double.parseDouble(cmd.getOptionValue("reduc_factor")); /* ============================= Generator parameters ============================= */ if (nbFiles < 0 || nbDags < 0 || nbJobs < 0) { System.err.println("[ERROR] Generator: Number of files & DAGs need to be positive."); formatter.printHelp("DAG Generator", options); System.exit(1); return; } Thread threads[] = new Thread[nbJobs]; int nbFilesCreated = 0; int count = 0; while (nbFilesCreated != nbFiles) { int launched = 0; for (int i = 0; i < nbJobs && count < nbFiles; i++) { String outFile = output.substring(0, output.lastIndexOf('.')).concat("-" + count + ".xml"); GeneratorThread gt = new GeneratorThread(maxU, nbTasks, edgeProb, levels, para, nbDags, rfactor, outFile, graph, debug); threads[i] = new Thread(gt); threads[i].setName("GeneratorThread-" + i); launched++; count++; threads[i].start(); } for (int i = 0; i < launched; i++) { try { threads[i].join(); nbFilesCreated++; } catch (InterruptedException e) { e.printStackTrace(); } } } }
From source file:io.coala.eve3.Eve3Test.java
public static void main(String[] args) { try {/*from w w w . j a v a 2 s . c o m*/ final LocalConfig config = LocalConfig.builder().withId(agentName) .withProvider(Invoker.class, Eve3Invoker.class).build(); final LocalBinder binder = Guice4LocalBinder.of(config); final List<URI> endpoints = binder.inject(Eve3Exposer.class).exposeAs(MyExposableService.class, new MyExposing()); LOG.trace("Exposed {} at endpoints: {}", MyExposableService.class.getSimpleName(), endpoints); Runtime.getRuntime().addShutdownHook(new Thread(() -> { System.err.println("SHUTTING DOWN EVE HTTP DAEMON"); })); // Runtime.getRuntime().exit( 0 ); } catch (final Exception e) { e.printStackTrace(); System.exit(e.hashCode()); } }
From source file:com.bluemarsh.jswat.console.Main.java
/** * Kicks off the application.// w w w . java 2 s. c o m * * @param args the command line arguments. */ public static void main(String[] args) { // // An attempt was made early on to use the Console class in java.io, // but that is not designed to handle asynchronous output from // multiple threads, so we just use the usual System.out for output // and System.in for input. Note that automatic flushing is used to // ensure output is shown in a timely fashion. // // // Where console mode seems to work: // - bash // - emacs // // Where console mode does not seem to work: // - NetBeans: output from event listeners is never shown and the // cursor sometimes lags behind the output // // Turn on flushing so printing the prompt will flush // all buffered output generated from other threads. PrintWriter output = new PrintWriter(System.out, true); // Make sure we have the JPDA classes. try { Bootstrap.virtualMachineManager(); } catch (NoClassDefFoundError ncdfe) { output.println(NbBundle.getMessage(Main.class, "MSG_Main_NoJPDA")); System.exit(1); } // Ensure we can create the user directory by requesting the // platform service. Simply asking for it has the desired effect. PlatformProvider.getPlatformService(); // Define the logging configuration. LogManager manager = LogManager.getLogManager(); InputStream is = Main.class.getResourceAsStream("logging.properties"); try { manager.readConfiguration(is); } catch (IOException ioe) { ioe.printStackTrace(); System.exit(1); } // Print out some useful debugging information. logSystemDetails(); // Add a shutdown hook to make sure we exit cleanly. Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { // Save the command aliases. CommandParser parser = CommandProvider.getCommandParser(); parser.saveSettings(); // Save the runtimes to persistent storage. RuntimeManager rm = RuntimeProvider.getRuntimeManager(); rm.saveRuntimes(); // Save the sessions to persistent storage and have them // close down in preparation to exit. SessionManager sm = SessionProvider.getSessionManager(); sm.saveSessions(true); } })); // Initialize the command parser and load the aliases. CommandParser parser = CommandProvider.getCommandParser(); parser.loadSettings(); parser.setOutput(output); // Create an OutputAdapter to display debuggee output. OutputAdapter adapter = new OutputAdapter(output); SessionManager sessionMgr = SessionProvider.getSessionManager(); sessionMgr.addSessionManagerListener(adapter); // Create a SessionWatcher to monitor the session status. SessionWatcher swatcher = new SessionWatcher(); sessionMgr.addSessionManagerListener(swatcher); // Create a BreakpointWatcher to monitor the breakpoints. BreakpointWatcher bwatcher = new BreakpointWatcher(); sessionMgr.addSessionManagerListener(bwatcher); // Add the watchers and adapters to the open sessions. Iterator<Session> iter = sessionMgr.iterateSessions(); while (iter.hasNext()) { Session s = iter.next(); s.addSessionListener(adapter); s.addSessionListener(swatcher); } // Find and run the RC file. try { runStartupFile(parser, output); } catch (IOException ioe) { logger.log(Level.SEVERE, null, ioe); } // Process command line arguments. try { processArguments(args); } catch (ParseException pe) { // Report the problem and keep going. System.err.println("Option parsing failed: " + pe.getMessage()); logger.log(Level.SEVERE, null, pe); } // Display a helpful greeting. output.println(NbBundle.getMessage(Main.class, "MSG_Main_Welcome")); if (jdbEmulationMode) { output.println(NbBundle.getMessage(Main.class, "MSG_Main_Jdb_Emulation")); } // Enter the main loop of processing user input. BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); while (true) { // Keep the prompt format identical to jdb for compatibility // with emacs and other possible wrappers. output.print("> "); output.flush(); try { String command = input.readLine(); // A null value indicates end of stream. if (command != null) { performCommand(output, parser, command); } // Sleep briefly to give the event processing threads, // and the automatic output flushing, a chance to catch // up before printing the input prompt again. Thread.sleep(250); } catch (InterruptedException ie) { logger.log(Level.WARNING, null, ie); } catch (IOException ioe) { logger.log(Level.SEVERE, null, ioe); output.println(NbBundle.getMessage(Main.class, "ERR_Main_IOError", ioe)); } catch (Exception x) { // Don't ever let an internal bug (e.g. in the command parser) // hork the console, as it really irritates people. logger.log(Level.SEVERE, null, x); output.println(NbBundle.getMessage(Main.class, "ERR_Main_Exception", x)); } } }
From source file:com.loy.MicroServiceConsole.java
public static void main(String[] args) throws SQLException { Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override/*from w w w.ja v a 2s .c o m*/ public void run() { killProcess(); } })); String[] arg = { "-tcp", "-tcpAllowOthers" }; Server server = Server.createTcpServer(arg); server.start(); init(); }
From source file:com.vangent.hieos.empi.pixpdq.loader.PIDFeedRandomLoader.java
/** * * @param args/* w ww. j a va2 s. c om*/ */ public static void main(String[] args) { PIDFeedRandomLoader pfl = new PIDFeedRandomLoader(); long start = System.currentTimeMillis(); Thread[] threads = new Thread[MAX_THREADS]; for (int i = 0; i < MAX_THREADS; i++) { PIDFeedRunnable pidFeedRunnable = pfl.getPIDFeedRunnable(TEMPLATE, ENTERPRISE_ASSIGNING_AUTHORITY, LOCAL_ASSIGNING_AUTHORITY, RUN_COUNT_PER_THREAD, ENDPOINT); threads[i] = new Thread(pidFeedRunnable); threads[i].start(); } for (int i = 0; i < threads.length; i++) { try { threads[i].join(); } catch (InterruptedException ignore) { } } long elapsedTime = System.currentTimeMillis() - start; double txnSec = ((double) MAX_THREADS * (double) RUN_COUNT_PER_THREAD) / ((double) elapsedTime / 1000.0); System.out.println(" done ... TOTAL TIME = " + elapsedTime + "ms" + ", txn/sec = " + txnSec); }
From source file:awskinesis.AmazonKinesisApplicationSample.java
public static void main(String[] args) throws Exception { init();//from www.j av a 2 s .c o m if (args.length == 1 && "delete-resources".equals(args[0])) { deleteResources(); return; } String workerId = InetAddress.getLocalHost().getCanonicalHostName() + ":" + UUID.randomUUID(); KinesisClientLibConfiguration kinesisClientLibConfiguration = new KinesisClientLibConfiguration( SAMPLE_APPLICATION_NAME, SAMPLE_APPLICATION_STREAM_NAME, credentialsProvider, workerId) .withRegionName("cn-north-1"); kinesisClientLibConfiguration.withInitialPositionInStream(SAMPLE_APPLICATION_INITIAL_POSITION_IN_STREAM); IRecordProcessorFactory recordProcessorFactory = new AmazonKinesisApplicationRecordProcessorFactory(); final Worker worker = new Worker(recordProcessorFactory, kinesisClientLibConfiguration); System.out.printf("Running %s to process stream %s as worker %s...\n", SAMPLE_APPLICATION_NAME, SAMPLE_APPLICATION_STREAM_NAME, workerId); int exitCode = 0; try { worker.run(); } catch (Throwable t) { System.err.println("Caught throwable while processing data."); t.printStackTrace(); exitCode = 1; } // add a shutdown hook to stop the server Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { LOG.info("########### shoutdown begin...."); worker.shutdown(); try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } LOG.info("########### shoutdown end...."); } })); System.exit(exitCode); }
From source file:herddb.server.ServerMain.java
public static void main(String... args) { try {// w w w .j a v a2s . c o m LOG.log(Level.INFO, "Starting HerdDB version {0}", herddb.utils.Version.getVERSION()); Properties configuration = new Properties(); boolean configFileFromParameter = false; for (int i = 0; i < args.length; i++) { String arg = args[i]; if (!arg.startsWith("-")) { File configFile = new File(args[i]).getAbsoluteFile(); LOG.log(Level.INFO, "Reading configuration from {0}", configFile); try (InputStreamReader reader = new InputStreamReader(new FileInputStream(configFile), StandardCharsets.UTF_8)) { configuration.load(reader); } configFileFromParameter = true; } else if (arg.equals("--use-env")) { System.getenv().forEach((key, value) -> { System.out.println("Considering env as system property " + key + " -> " + value); System.setProperty(key, value); }); } else if (arg.startsWith("-D")) { int equals = arg.indexOf('='); if (equals > 0) { String key = arg.substring(2, equals); String value = arg.substring(equals + 1); System.setProperty(key, value); } } } if (!configFileFromParameter) { File configFile = new File("conf/server.properties").getAbsoluteFile(); LOG.log(Level.INFO, "Reading configuration from {0}", configFile); if (configFile.isFile()) { try (InputStreamReader reader = new InputStreamReader(new FileInputStream(configFile), StandardCharsets.UTF_8)) { configuration.load(reader); } } } System.getProperties().forEach((k, v) -> { String key = k + ""; if (!key.startsWith("java") && !key.startsWith("user")) { configuration.put(k, v); } }); LogManager.getLogManager().readConfiguration(); Runtime.getRuntime().addShutdownHook(new Thread("ctrlc-hook") { @Override public void run() { System.out.println("Ctrl-C trapped. Shutting down"); ServerMain _brokerMain = runningInstance; if (_brokerMain != null) { _brokerMain.close(); } } }); runningInstance = new ServerMain(configuration); runningInstance.start(); runningInstance.join(); } catch (Throwable t) { t.printStackTrace(); System.exit(1); } }
From source file:ab.demo.MainEntry.java
public static void main(String args[]) { LoggingHandler.initConsoleLog();/*from w w w .ja v a 2 s. c o m*/ //args = new String[]{"-su"}; Options options = new Options(); options.addOption("s", "standalone", false, "runs the reinforcement learning agent in standalone mode"); options.addOption("p", "proxyPort", true, "the port which is to be used by the proxy"); options.addOption("h", "help", false, "displays this help"); options.addOption("n", "naiveAgent", false, "runs the naive agent in standalone mode"); options.addOption("c", "competition", false, "runs the naive agent in the server/client competition mode"); options.addOption("u", "updateDatabaseTables", false, "executes CREATE TABLE IF NOT EXIST commands"); options.addOption("l", "level", true, "if set the agent is playing only in this one level"); options.addOption("m", "manual", false, "runs the empirical threshold determination agent in standalone mode"); options.addOption("r", "real", false, "shows the recognized shapes in a new frame"); CommandLineParser parser = new DefaultParser(); CommandLine cmd; StandaloneAgent agent; Properties properties = new Properties(); InputStream configInputStream = null; try { Class.forName("org.sqlite.JDBC"); //parse configuration file configInputStream = new FileInputStream("config.properties"); properties.load(configInputStream); } catch (IOException exception) { exception.printStackTrace(); } catch (ClassNotFoundException exception) { exception.printStackTrace(); } finally { if (configInputStream != null) { try { configInputStream.close(); } catch (IOException exception) { exception.printStackTrace(); } } } String dbPath = properties.getProperty("db_path"); String dbUser = properties.getProperty("db_user"); String dbPass = properties.getProperty("db_pass"); DBI dbi = new DBI(dbPath, dbUser, dbPass); QValuesDAO qValuesDAO = dbi.open(QValuesDAO.class); GamesDAO gamesDAO = dbi.open(GamesDAO.class); MovesDAO movesDAO = dbi.open(MovesDAO.class); ProblemStatesDAO problemStatesDAO = dbi.open(ProblemStatesDAO.class); try { cmd = parser.parse(options, args); if (cmd.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("help", options); return; } int proxyPort = 9000; if (cmd.hasOption("proxyPort")) { proxyPort = Integer.parseInt(cmd.getOptionValue("proxyPort")); logger.info("Set proxy port to " + proxyPort); } Proxy.setPort(proxyPort); LoggingHandler.initFileLog(); if (cmd.hasOption("standalone")) { agent = new ReinforcementLearningAgent(gamesDAO, movesDAO, problemStatesDAO, qValuesDAO); } else if (cmd.hasOption("naiveAgent")) { agent = new NaiveStandaloneAgent(); } else if (cmd.hasOption("manual")) { agent = new ManualGamePlayAgent(gamesDAO, movesDAO, problemStatesDAO); } else if (cmd.hasOption("competition")) { System.out.println("We haven't implemented a competition ready agent yet."); return; } else { System.out.println("Please specify which solving strategy we should be using."); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("help", options); return; } if (cmd.hasOption("updateDatabaseTables")) { qValuesDAO.createTable(); gamesDAO.createTable(); movesDAO.createTable(); problemStatesDAO.createTable(); problemStatesDAO.createObjectsTable(); } if (cmd.hasOption("level")) { agent.setFixedLevel(Integer.parseInt(cmd.getOptionValue("level"))); } if (cmd.hasOption("real")) { ShowSeg.useRealshape = true; Thread thread = new Thread(new ShowSeg()); thread.start(); } } catch (UnrecognizedOptionException e) { System.out.println("Unrecognized commandline option: " + e.getOption()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("help", options); return; } catch (ParseException e) { System.out.println( "There was an error while parsing your command line input. Did you rechecked your syntax before running?"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("help", options); return; } agent.run(); }
From source file:net.bluehornreader.service.ServiceManager.java
public static void main(String[] args) throws Exception { String webappPath = null;/*from w w w .ja v a 2 s . co m*/ if (Utils.isInJar()) { if (args.length != 1 || isHelp(args)) { System.err.println("Usage:\njava -Dlog4j.configuration=file:<PATH>/log4j.properties " + "-jar bluehorn-reader-<VERSION>.one-jar.jar <PATH>/config.properties"); System.exit(1); } } else { if ((args.length != 2 && args.length != 1) || isHelp(args)) { System.err.println("Usage:\njava -Dlog4j.configuration=file:<PATH>/log4j.properties " + "net.bluehornreader.service.ServiceManager <PATH>/config.properties <PATH>/webapp"); System.exit(1); } if (args.length == 2) { webappPath = args[1]; } else { URL url = ServiceManager.class.getClassLoader() .getResource("net/bluehornreader/model/Article.class"); if (url != null) { webappPath = url.getPath().replace("target/classes/net/bluehornreader/model/Article.class", "") + "src/main/webapp"; if (new File(webappPath).isDirectory()) { LOG.info("Found webapp folder at " + webappPath); } else { webappPath = null; } } if (webappPath == null) { System.err.println( "Cannot locate the webapp folder. You'll have to specify it manually, as the second parameter."); System.exit(1); } } } if (webappPath == null) { webappPath = new File(".").getCanonicalPath(); // just to have a valid folder to pass } String configFileName = args[0]; Config.setup(configFileName); final ServiceManager serviceManager = new ServiceManager(webappPath); Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { LOG.info("***************************************************************************\n\n"); LOG.info("Shutting down ServiceManager ..."); serviceManager.shutdown(); } })); }
From source file:com.weibo.wesync.client.NHttpClient2.java
public static void main(String[] args) throws Exception { RSAPublicKey publicKey = RSAEncrypt.loadPublicKey("D:\\weibo\\meyou_gw\\conf\\public.pem"); // // w ww .j a va 2 s . c om byte[] cipher = RSAEncrypt.encrypt(publicKey, password.getBytes()); password = RSAEncrypt.toHexString(cipher); // HTTP parameters for the client HttpParams params = new SyncBasicHttpParams(); params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 30000) .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000) .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024) .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true); // Create HTTP protocol processing chain HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { // Use standard client-side protocol interceptors new RequestContent(), new RequestTargetHost(), new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() }); // Create client-side HTTP protocol handler HttpAsyncRequestExecutor protocolHandler = new HttpAsyncRequestExecutor(); // Create client-side I/O event dispatch final IOEventDispatch ioEventDispatch = new DefaultHttpClientIODispatch(protocolHandler, params); // Create client-side I/O reactor IOReactorConfig config = new IOReactorConfig(); config.setIoThreadCount(1); final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(config); // Create HTTP connection pool BasicNIOConnPool pool = new BasicNIOConnPool(ioReactor, params); // Limit total number of connections to just two pool.setDefaultMaxPerRoute(2); pool.setMaxTotal(1); // Run the I/O reactor in a separate thread Thread t = new Thread(new Runnable() { public void run() { try { // Ready to go! ioReactor.execute(ioEventDispatch); } catch (InterruptedIOException ex) { System.err.println("Interrupted"); } catch (IOException e) { System.err.println("I/O error: " + e.getMessage()); } System.out.println("Shutdown"); } }); // Start the client thread t.start(); // Create HTTP requester // HttpAsyncRequester requester = new HttpAsyncRequester( // httpproc, new DefaultConnectionReuseStrategy(), params); // Execute HTTP GETs to the following hosts and HttpHost[] targets = new HttpHost[] { // new HttpHost("123.125.106.28", 8093, "http"), // new HttpHost("123.125.106.28", 8093, "http"), // new HttpHost("123.125.106.28", 8093, "http"), // new HttpHost("123.125.106.28", 8093, "http"), // new HttpHost("123.125.106.28", 8093, "http"), // new HttpHost("123.125.106.28", 8093, "http"), // new HttpHost("123.125.106.28", 8093, "http"), // new HttpHost("123.125.106.28", 8093, "http"), // new HttpHost("123.125.106.28", 8093, "http"), // new HttpHost("123.125.106.28", 8093, "http"), // new HttpHost("123.125.106.28", 8093, "http"), new HttpHost("123.125.106.28", 8082, "http") }; final CountDownLatch latch = new CountDownLatch(targets.length); int callbackId = 0; for (int i = 0; i < 1; i++) { for (final HttpHost target : targets) { BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/wesync"); // String usrpwd = Base64.encodeBase64String((username + ":" + password).getBytes()); // request.setHeader("authorization", "Basic " + usrpwd); request.setHeader("uid", "2565640713"); Meyou.MeyouPacket packet = null; if (callbackId == 0) { packet = Meyou.MeyouPacket.newBuilder().setCallbackId(String.valueOf(callbackId++)) .setSort(MeyouSort.notice).build(); } else { packet = Meyou.MeyouPacket.newBuilder().setCallbackId(String.valueOf(callbackId++)) .setSort(MeyouSort.wesync).build(); } ByteArrayEntity entity = new ByteArrayEntity(packet.toByteArray()); request.setEntity(entity); // BasicHttpRequest request = new BasicHttpRequest("GET", "/test.html"); System.out.println("send ..."); HttpAsyncRequester requester = new HttpAsyncRequester(httpproc, new DefaultConnectionReuseStrategy(), params); requester.execute(new BasicAsyncRequestProducer(target, request), new BasicAsyncResponseConsumer(), pool, new BasicHttpContext(), // Handle HTTP response from a callback new FutureCallback<HttpResponse>() { public void completed(final HttpResponse response) { StatusLine status = response.getStatusLine(); int code = status.getStatusCode(); if (code == 200) { try { latch.countDown(); DataInputStream in; in = new DataInputStream(response.getEntity().getContent()); int packetLength = in.readInt(); int start = 0; while (packetLength > 0) { ByteArrayOutputStream outstream = new ByteArrayOutputStream( packetLength); byte[] buffer = new byte[1024]; int len = 0; while (start < packetLength && (len = in.read(buffer, start, packetLength)) > 0) { outstream.write(buffer, 0, len); start += len; } Meyou.MeyouPacket packet0 = Meyou.MeyouPacket .parseFrom(outstream.toByteArray()); System.out.println(target + "->" + packet0); if ((len = in.read(buffer, start, 4)) > 0) { packetLength = Util.readPacketLength(buffer); } else { break; } } } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { System.out.println("error code=" + code + "|" + status.getReasonPhrase()); } } public void failed(final Exception ex) { latch.countDown(); System.out.println(target + "->" + ex); } public void cancelled() { latch.countDown(); System.out.println(target + " cancelled"); } }); Thread.sleep((long) (Math.random() * 10000)); } } // latch.await(); // System.out.println("Shutting down I/O reactor"); // ioReactor.shutdown(); // System.out.println("Done"); }