import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.Charset; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CountDownLatch; public class Task implements Runnable { private final CountDownLatch startLatch; public Task(CountDownLatch startLatch) { this.startLatch = startLatch; } @Override public void run() { try { startLatch.countDown(); System.out.println(thread.currentThread ().getName() + "start" + system.currentTimemillis ()); // Thread.sleep(new Random().nextInt(10)*100); getRequest(); } catch (Exception e) { e.printStackTrace(); } finally { } } private static void getRequest() { try { URL url = new URL("https://blog.csdn.net/qq_14996421/article/details/102840681"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.connect(); InputStream inputStream = conn.getInputStream(); byte[] data = new byte[1024]; StringBuffer sb = new StringBuffer(); int length = 0; while ((length = inputStream.read(data)) ! = -1) { String s = new String(data, Charset.forName("utf-8")); sb.append(s); } String message = sb.toString(); Map<String, Object> map = new HashMap<>(); map.put("json", message); inputStream.close(); conn.disconnect(); } catch (IOException e) { e.printStackTrace(); System.out.println("test"); } } public static void main(String[] args) { getRequest(); }}Copy the code
import java.text.DecimalFormat; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; Public class SdkConcurrencyTest {public static int threadNum = 6; public static CountDownLatch countDownLatch = new CountDownLatch(threadNum); Public static void main(String[] args) throws InterruptedException {// Initialize the thread pool Executors.newCachedThreadPool(); Long beginTime= system.currentTimemillis (); // loop to initialize thread for(int I = 0; i < threadNum; i++){ Task target = new Task(countDownLatch); pool.execute(target); } // Close the thread pool pool.shutdown(); Countdownlatch.await () countdownlatch.await () countdownlatch.await (); Long totalTime = System.currentTimemillis ()-beginTime; Thread.sleep(1000); Df =new DecimalFormat(".00"); // Set DecimalFormat to 2 digits. System. Out.println (" sent a total of "+ threadNum +" requests "+" \ n "+" -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - "+" \ n "+" total time for: "+ totalTime +" \ n "+" -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - "+" \ n "+" QPS for "+ df. The format ((double) threadNum * 1000 / totalTime) +"/s "); }}Copy the code