Java >> Tutoriel Java >  >> Java

Comment créer des threads Java (exemples java pour créer des threads) ?

Les threads sont des processus légers. Un processus est un programme complet tandis qu'un thread est une petite tâche qui peut ou non être indépendante . Chaque programme Java contient un thread principal qui est responsable de l'exécution de la méthode principale. Les threads sont essentiellement utilisés pour les tâches asynchrones, c'est-à-dire pour le traitement en arrière-plan et pour utiliser le concept de multitâche.

En Java, les threads peuvent être créés de deux manières :

  1. En étendant la classe Thread
  2. En implémentant l'interface Runnable

1) Programme pour créer un thread en étendant la classe Thread

Dans ce programme, une classe nommée newThread étend la classe Thread qui est une classe intégrée de Java a des fonctions comme run(), stop(), start(), destroy() etc. La méthode start sera invoquée sur un objet de la classe newThread . Ce fil continuera à fonctionner jusqu'à 10 000 fois selon la logique.

class newThread extends Thread{
	private int threadid;
	//this is a constructor to take the arguments in a thread
	public newThread(int id) 
	{ 
		//here threadid will be 1
		threadid = id; 
	}
	public void run() {
		/*run() method is responsible for running a thread ,all the programming logic will
		be contain by this thread i.e what u want your thread to do */
		for(int i=0; i<10000 ; i++) {
			System.out.println(threadid + " : " + i);
		}
	}
}

public class CreateThreadByExtending {
	public static void main(String[] args) {
		//creating an object of newThread class and sending 1 as an argument
		newThread thread1=new newThread(1);
		//start() function is use to start the thread 
		thread1.start();
	}
}

Sortie

1 : 0
2 : 1
3 : 2
4 : 3
upto 9999

2) Programme pour créer un thread en implémentant l'interface Runnable

Dans ce programme, une classe nommée newThread1 implémente une interface Runnable qui est une interface intégrée de java. Ici, un objet sera créé de la classe newThread1 et cet objet sera passé à la classe Thread pour invoquer la méthode d'exécution, car les objets de la classe newThread1 ne seront pas considérés comme un objet Thread.

class newThread1 implements Runnable{
	
	public void run() {
		/*run() method is responsible for running a thread ,all the programming logic will
		  be contain by this thread i.e what u want your thread to do */
		System.out.println("Thread is running.........");
	}
}
public class CreateThreadByImplementing {
	public static void main(String[] args) {
		//creating an object of newThread class
        newThread1 m1=new newThread1();
        /*as class newThread class doesn't extend Thread class ,therefor its object will not be consider as
        thread object.We need to explicitily call Thread class object and passing the object of newThread class
        that implements runnable so run() method will be executed.*/
        Thread t1 =new Thread(m1);  
        //starting the thread
        t1.start(); 
	}
}

Sortie

Thread is running.......

Balise Java