Java Reference
In-Depth Information
Listing 6-46. A Class to Test a Producer/Consumer System with an Exchanger
// ExchangerProducerConsumerTest.java
package com.jdojo.threads;
import java.util.concurrent.Exchanger;
import java.util.ArrayList;
public class ExchangerProducerConsumerTest {
public static void main(String[] args) {
Exchanger<ArrayList<Integer>>exchanger = new Exchanger<>();
// The producer will produce 5 integers at a time
ExchangerProducer producer = new ExchangerProducer(exchanger, 5);
ExchangerConsumer consumer = new ExchangerConsumer(exchanger);
producer.start();
consumer.start();
}
}
Producer is filling the buffer with data...
Consumer is waiting to exchange the data...
Producer has produced:[1, 2, 3, 4, 5]
Producer is waiting to exchange the data...
...
The Executor Framework
A task is a logical unit of work, and typically a thread is used to represent and execute a task. Many aspects of task
execution should be considered before modeling it in a program. A few aspects of a task are as follows:
How it is created.
How it is submitted for execution.
How it is executed. Is it executed synchronously or asynchronously?
The time at which it is executed. Is it executed immediately upon submission or queued?
Which thread executes it? Is it executed in the thread that submits it or in another thread?
How do we get the result of a task when it is finished executing?
How do we know the error that occurs during its execution?
A task may be represented as a Runnable . If you want to manage tasks using threads, follow the steps described
below. You can create a class to represent a task.
Does it depend on other tasks to finish its execution?
 
Search WWH ::




Custom Search