synchronizedacquires intrinsic lock and the other thread has to wait until the lock is released.-
Problem: only one lock exists and all the other threads are blocked from running other synchronized methods.
-
Declare separate
lock<i>objects and synchronize code blocks as follows:Object lock1 = new Object(); public void method() { synchronized(lock1) { // block of code } }
-
- Way of managing many threads
-
ExecutorService- Has a managerial thread
-
Executorpublic class RunnerThreadPool implements Runnable { private int id; public RunnerThreadPool(int id) { this.id = id; } public void run() { System.out.println("Starting: " + id); try { Thread.sleep(5000); } catch(InterruptedException ie) { ie.printStackTrace(); } } public static void main(String[] args) { ExecutorService service = Executors.newFixedThreadPool(2); for(int i = 0; i < 5; i++) { service.submit(new RunnerThreadPool(i)); } service.shutdown(); try { service.awaitTermination(1, TimeUnit.DAYS); } catch(InterruptedException ie) { ie.printStackTrace(); } } }
-
- Used for controlling access to a resource.
- Syntax:
Semaphore semaphore = new Semaphore(<number-of-permits>);- Initialize with initial number of permits
sem.acquire();(M)- If there are enough permits, continues but if there are no permits, thein waits for permits.
sem.release();(M)- Releases a permit which increments the number of permits of the semaphore.
sem.availablePermits();- Returns the number of permits currently available.
-
Used to return results from thread executing method.
-
Syntax:
ExecutorService executor = Executors.newCachedThreadPool(); Future<Integer> future = executor.submit(new Callable<Integer>() { @Override public Integer call() { // some logic that assigns an integer value to 'var' return var; } }); try { System.out.println("Return value: " + future.get()); } catch(InterruptedException e) { e.printStackTrace(); } catch(ExecutionException e) { e.printStackTrace(); }