API Thread

Table des matières :

Overview

A thread is a thread of execution in a program. The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.
  • Every thread has a priority : Threads with higher priority are executed in preference to threads with lower priority.
    MIN_PRIORITY (1) <= priority <= MAX_PRIORITY (10).
    By default = NORM_PRIORITY (5).
  • Daemon : Each thread may or may not also be marked as a daemon.
The Java Virtual Machine exits when the only threads running are all daemon threads.

Methods to use:
  • Methods of Thread
    • public void start() : Causes this thread to begin execution. The Java Virtual Machine calls the run method of this thread.
    • public void interrupt() : Interrupts this thread.
    • deprecated method : Don't use the methods : stop() resume() suspend().
  • Static methods of Thread
    • public static void yield() : Causes the currently executing thread object to temporarily pause and allow other threads to execute.
    • public static void sleep(long millis) : the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds. The thread does not lose ownership of any monitors.
  • Methods of Object
    • public final void wait(long timeout) : Causes current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.
    • public final void notify() : Wakes up a single thread that is waiting on this object's monitor...
    • public final void notifyAll() : Wakes up all threads that are waiting on this object's monitor...
  • For details, see Sun API documentation

Exemples de création de Thread

Exemple d'une sous-classe de java.lang.Thread

class MyThread extends Thread { public MyThread() { super("Name of my Thread"); setPriority(4); // MIN_PRIORITY <= .. <= MAX_PRIORITY setDaemon(false); } public void run() { // code of the thread } }

Exemple d'une Thread créé en classe anonyme

Thread t = new Thread() { public void run(){ // code of the thread } }; t.start();

Destruction d'un Thread / Memory leek

Un Thread est automatiquement candidat pour être détruit (par le garbage collection) lorsque son exécution est terminée.
Parfois, certains programmeurs utilisent des instances de Thread au lieu de Runnable.
Attention, si on crée un Thread et que l'on exécute run(), et non start(), cela peut conduire à des memory leek, l'instance de Thread ne sera pas libéré ainsi que toutes les références qu'il contient.
Ne créer des instances de java.lang.Thread que si vous en avez réellement besoin.

Ci dessous un exemple avec une méthode ayant comme paramètre un flag indiquant d'utiliser ou non un nouveau Thread pour exécuter une partie du code.

Code invalide

public void doSomething(boolean a_useThread) { Thread t = new Thread() { public void run() { // do something } }; if (useThread) { t.start(); } else { t.run(); // Le Thread ne sera jamais libérer } }

Utiliser plutot le code suivant

public void doSomething(boolean a_useThread) { if (! useThread) { // do something } else { Thread t = new Thread() { public void run() { // do something } }; t.start(); } }

Utilisation de Runnable

public void doSomething(boolean a_useThread) { Runnable r = new Runnable() { public void run() { // do something } }; if (! useThread) { r.run(); } else { (new Thread(r)).start(); } }

Utilisation avec une autre méthode

public void doSomething() { // do something }
public void doSomething(boolean a_useThread) { if (!useThread) { doSomething(); } else { Thread t = new Thread() { public void run() { doSomething(); } }; t.start(); } }
Thread API 1.3
Thread API 1.4.2


Article extrait du site Loribel.com.
https://loribel.com/java/topics/java.api.thread.html