multithreading - Simultaneous access to a Java synchronized block using threads? -
how can 2 threads access synchronized block simultaneously? is, how can make 1 thread give chance other thread execute synchronized block, before thread finishes execution of same synchronized block?
see wait(), notify(), , notifyall().
edit: edit question incorrect. sleep() method not release monitor.
for example:
private static final object lock = new object(); public static void main(string[] args) { executorservice executorservice = executors.newfixedthreadpool(2); executorservice.execute(new one()); executorservice.execute(new two()); } static class 1 implements runnable { @override public void run() { synchronized (lock) { system.out.println("(one) own lock"); system.out.println("(one) giving lock , waiting"); try { lock.wait(); } catch (interruptedexception e) { system.err.println("(one) shouldn't have been interrupted"); } system.out.println("(one) have lock now"); } } } static class 2 implements runnable { @override public void run() { try { thread.sleep(100); } catch (interruptedexception e) { system.err.println("(two) shouldn't have been interrupted"); } synchronized (lock) { system.out.println("(two) own lock (two)"); system.out.println("(two) giving lock using notify()"); lock.notify(); } } }
Comments
Post a Comment