Java Reference
In-Depth Information
24 Thread.sleep(( int )(Math.random() * 10000 ));
25 }
26 }
27 catch (InterruptedException ex) {
28 ex.printStackTrace();
29 }
30 }
31 }
32
33 // A task for reading and deleting an int from the buffer
34 private static class ConsumerTask implements Runnable {
35 public void run() {
36 try {
37 while ( true ) {
38 System.out.println( "\t\t\tConsumer reads " + buffer.take());
39 // Put the thread into sleep
40 Thread.sleep(( int )(Math.random() * 10000 ));
41 }
42 }
43 catch (InterruptedException ex) {
44 ex.printStackTrace();
45 }
46 }
47 }
48 }
consumer task
take
In Listing 30.7, you used locks and conditions to synchronize the Producer and Consumer
threads. This program does not use locks and conditions, because synchronization is already
implemented in ArrayBlockingQueue .
30.28 What is a blocking queue? What blocking queues are supported in Java?
30.29 What method do you use to add an element to an ArrayBlockingQueue ? What
happens if the queue is full?
30.30 What method do you use to retrieve an element from an ArrayBlockingQueue ?
What happens if the queue is empty?
Check
Point
30.12 Semaphores
Semaphores can be used to restrict the number of threads that access a shared resource.
Key
Point
In computer science, a semaphore is an object that controls the access to a common resource. Before
accessing the resource, a thread must acquire a permit from the semaphore. After finishing with
the resource, the thread must return the permit back to the semaphore, as shown in Figure 30.22.
semaphore
A thread accessing a shared resource.
Acquire a permit from a semaphore.
Wait if the permit is not available.
semaphore.acquire();
Access the resource
semaphore.release();
Release the permit to the semaphore.
F IGURE 30.22
A limited number of threads can access a shared resource controlled by
a semaphore.
 
 
 
Search WWH ::




Custom Search