0

Could some one explain why second thread taking much lesser time for same process

public class Main {

  public static void main(String[] args) {

    final String[] test = {
        "YKWV57I4OYEBH1JMMLGDRTH66HO6OIOJHMLASA29WHPD5OOYMQY0URO05901PXAOQUU2KDIGWOTMX0YR7LBHE7Z6Z55R9GG8NWD13V70BRG5L70L65GHZFNI6ZEA349BHLDO3LQLNS6RGL9NQKMKK1KJ91AH68PKIGYM2Q772WWWAV20ZRYXUWCERXQUW8SF67OG4LEY19VPJ9ZXO9II8S39JRJTMOI9JW4CYYUGJ2YYWE7C6FTL71NJKLEACUUKW1O68P0EDMR3XGWJY1F6179Y87B7JCYBY35QEAI67YJQ944APUJX7SKD8DR9XIH6KB0V0TMLKPCNOSFIMSONH822GSKDGR3B05M1T9YK8RH7GPTQDVINR1SKG92OCMNW0GZNBV77JYOJ32O3CLJWCIZUQXUZAMEKQLCO8E47UCUV64U630GHAZ34M05QI7504ZR53KLSYSDKFQLE3JSZDKL4VLGY456LKND4Z49Y3QCED2YOSMHH7FVZGA1HXM"};


    long s= System.currentTimeMillis();
    new Thread(() -> {
      test[0] = test[0].replaceAll("E","  11111  ");
      System.out.println(test[0]+"  is test[0] for thread 1");
    }).start();
    long e= System.currentTimeMillis();
    System.out.println(e-s + " in t1");

    long s1= System.currentTimeMillis();

    new Thread(() -> {
      test[0] = test[0].replaceAll("E","  22222  ");
      System.out.println(test[0]+"  is test[0] for thread 2");
    }).start();

    long e1= System.currentTimeMillis();



    System.out.println(e1-s1 +" in t2");

  }
}
3
  • Don't see much different in my machine, e.g. I see 2 in t1. 1 in t2. Commented Oct 4, 2022 at 8:18
  • 4
    You are not waiting for the completion of the threads, hence you’re only measuring how long it takes to start the threads, which boils down to how long it takes to convert a lambda expression into a Runnable. Which can be longer for the first lambda expression as explained in this answer. However, if you fix the code to wait for the completion of the actual operation, you’re still not comparing similar operations. After the first replacement operation, there are no Es in the string. Commented Oct 4, 2022 at 13:13
  • 3
    Recommended read How do I write a correct micro-benchmark in Java? Commented Oct 4, 2022 at 13:15

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.