background preloader

Synchronization

Facebook Twitter

Executors (Java 2 Platform SE 5.0) Java.lang.Object java.util.concurrent.Executors public class Executorsextends Object Factory and utility methods for Executor, ExecutorService, ScheduledExecutorService, ThreadFactory, and Callable classes defined in this package. This class supports the following kinds of methods: Methods that create and return an ExecutorService set up with commonly useful configuration settings. Methods that create and return a ScheduledExecutorService set up with commonly useful configuration settings. Methods that create and return a "wrapped" ExecutorService, that disables reconfiguration by making implementation-specific methods inaccessible. Since: newFixedThreadPool public static ExecutorService newFixedThreadPool(int nThreads) Creates a thread pool that reuses a fixed set of threads operating off a shared unbounded queue. Parameters: nThreads - the number of threads in the pool Returns: the newly created thread pool threadFactory - the factory to use when creating new threads newSingleThreadExecutor.

Java et la synchronisation. La synchronisation est un élément essentiel dès lors que vous utilisez plusieurs threads (c'est-à-dire dans quasiment toutes les applications). En effet, sans synchronisation, il est impossible de développer une application robuste qui fonctionne quel que soit l'entrelacement de l'exécution des threads. Pré requis : Connaître la syntaxe Java, la programmation orientée objet et le fonctionnement général des threads et de l'ordonnanceur. I-A. Présentation des problèmes généraux▲ Tout d'abord, voyons un problème de synchronisation classique. Plusieurs entités récepteurs (threads) reçoivent une demande d'un client.

Ils peuvent déposer des travaux dans une file. Plusieurs problèmes de synchronisation se posent ici : I-B. Le but est de résoudre ces problèmes généraux, auquels on peut dans la majorité des cas se ramener. Pour les résoudre correctement, il faut assurer : L'exclusion mutuelle permet de résoudre les problèmes de synchronisations 1, 3 et 5 de la présentation des problèmes généraux. Les AsyncTask. Bonjour chers amis développeurs Android ! Aujourd’hui nous allons voir comment fonctionne la classe AsyncTask. Comme son nom l’indique, une AsyncTask permet de réaliser des tâches de manière asynchrone, à la manière de la classe Thread.

L’avantage de l’AsyncTask est sa simplicité d’utilisation et d’implémentation. Le Thread secondaire est créé automatiquement et la communication entre les différents Thread est simplifiée. Lors du développement d’une application, il faut bien avoir en tête que toutes les tâches consommatrices de ressources (requêtes http, calculs lourds, …) doivent se faire dans un Thread séparé. Mise en place du projet Nous allons donc d’abord créer un nouveau projet appelé AsyncBigCalcul. L’activité principale Nous allons d’abord récupérer les composants définis dans le layout puis ajouter un listener sur le bouton afin qu’à chaque appui on exécute une nouvelle instance de BigCalcul. La classe BigCalcul Ce qui donnera : AsyncTask. Class Overview AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent package such as Executor, ThreadPoolExecutor and FutureTask. An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread.

Developer Guides For more information about using tasks and threads, read the Processes and Threads developer guide. Usage Here is an example of subclassing: Once created, a task is executed very simply: AsyncTask's generic types The 4 steps. ReentrantLock (Java 2 Platform SE 5.0) Java.lang.Object java.util.concurrent.locks.ReentrantLock All Implemented Interfaces: Serializable, Lock public class ReentrantLockextends Objectimplements Lock, Serializable A reentrant mutual exclusion Lock with the same basic behavior and semantics as the implicit monitor lock accessed using synchronized methods and statements, but with extended capabilities. A ReentrantLock is owned by the thread last successfully locking, but not yet unlocking it. The constructor for this class accepts an optional fairness parameter. It is recommended practice to always immediately follow a call to lock with a try block, most typically in a before/after construction such as: class X { private final ReentrantLock lock = new ReentrantLock(); // ... public void m() { lock.lock(); // block until condition holds try { // ... method body } finally { lock.unlock() } } } This lock supports a maximum of 2147483648 recursive locks by the same thread.

Since: See Also: Serialized Form ReentrantLock public ReentrantLock() Java - What does 'synchronized' mean.