multithreading - How does a synchronized method work in Java? -


i need method run once background no matter how many threads call it. found partial solution using code code:

public static void async(final int a){     thread th = new thread(new runnable() {         @override         public void run() {             meth(a);         }     });     th.start(); } public static synchronized void meth(final int a){     try {         thread.sleep(1000);         system.out.println(a);     } catch (interruptedexception ex) {         logger.getlogger(simple.class.getname()).log(level.severe, null, ex);     } } 

but when test that:

system.out.println("start"); async(11); async(12); async(13); async(14); async(15); async(16); async(17); async(18); async(19); system.out.println("end"); 

i got results:

start end 11 19 18 17 15 16 14 13 12

is there wrong code? why results not in same order call?

edited after using thread.join

public static object obg = new object();  public static void async(final int a){     thread th = new thread(new runnable() {         @override         public void run() {             meth(a);         }     });     th.start();     try {         th.join();     } catch (interruptedexception ex) {         logger.getlogger(simple.class.getname()).log(level.severe, null, ex);     } }  public static synchronized void meth(final int a){     try {         thread.sleep(1000);         system.out.println(a);     } catch (interruptedexception ex) {         logger.getlogger(simple.class.getname()).log(level.severe, null, ex);     } } 

i got result cancled background work :

start 11 12 13 14 15 16 17 18 19 end

thread.join didn't gave me results wish

edit third time give example other languages.

i tried same code in c#

 static void main(string[] args)     {         console.writeline("start");         async(11);         async(12);         async(13);         async(14);         async(15);         async(16);         async(17);         async(18);         console.writeline("end");     }      static object o = new object();     public static void async(int a){         new thread(() =>         {             lock (o)             {                 thread.sleep(1000);                 console.writeline(a);             }         }).start();     } 

the results in same order

test results swift language same c#

so question : how achieve results in java

edit : results of using newly created thread in join

code :

public static void main(string[] args) throws exception {     system.out.println("start");     async(19,async(18,async(17,async(16,async(15,async(14,async(13,async(12,async(11,null)))))))));     system.out.println("end"); }  public static object obg = new object();  public static thread async(final int a,final thread other){     thread th = new thread(new runnable() {         @override         public void run() {             meth(a);         }     });     th.start();     try {         if(other!=null){             other.join();         }     } catch (interruptedexception ex) {         logger.getlogger(simple.class.getname()).log(level.severe, null, ex);     }     return th; }  public static synchronized void meth(final int a){     try {         thread.sleep(1000);         system.out.println(a);     } catch (interruptedexception ex) {         logger.getlogger(simple.class.getname()).log(level.severe, null, ex);     } } 

results :

start 11 12 13 14 15 16 17 18 end 19

background work canceled.

your main thread starts 9 others, giving each child thread different a, , first thing 9 of child threads sleep 1 second.

the timing resolution in thread.sleep() call undefined---it depends on underlying operating system---and it's quite possible of threads elgible wake on same tick of system clock.

java makes no guarantee threads start running in order thread objects start()ed, , makes no guarantee wake in order in went sleep.

any time want things happen in order, best way make happen of things in single thread.


i need section run sequentially...i don't want run twice or more @ same time...i still want run in background.

ok., now.

you want use java.util.concurrent.executors.newsinglethreadexecutor(). function return thread pool single worker thread.

the worker thread run tasks submit pool "in background", , run them, 1 @ time, in order submitted.

static final executorservice singlethreadexecutor = executors.newsinglethreadexecutor();  public static void async(final int a) {     singlethreadexecutor.submit(new runnable() {         @override         public void run() {             meth(a);         }     }); } 

Comments

Popular posts from this blog

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.Error occurred in starting fork -

windows - Debug iNetMgr.exe unhandle exception System.Management.Automation.CmdletInvocationException -

configurationsection - activeMq-5.13.3 setup configurations for wildfly 10.0.0 -