Come eseguire più thread in Java contemporaneamente - Esempio

Sommario:

Come eseguire più thread in Java contemporaneamente - Esempio
Come eseguire più thread in Java contemporaneamente - Esempio

Video: Come eseguire più thread in Java contemporaneamente - Esempio

Video: Come eseguire più thread in Java contemporaneamente - Esempio
Video: #2 Mysql: il database open source più famoso al mondo. 2024, Maggio
Anonim

Questo articolo spiega come eseguire più thread in Java. Ti consigliamo di eseguire più thread per creare un programma che elabori più azioni contemporaneamente; più CPU ha il tuo computer, più processi può essere eseguito contemporaneamente.

Passi

12477945 1
12477945 1

Passaggio 1. Inserisci il seguente codice:

public void run()

Questo codice fornisce un punto di partenza per l'esecuzione di più thread

12477945 2
12477945 2

Passaggio 2. Inserisci il seguente codice:

Thread(Eseguibile threadObj, String threadName);

  • '

    threadObj

    ' è la classe che avvia il thread eseguibile e '

    threadName

  • ' è il nome del thread.
12477945 3
12477945 3

Passaggio 3. Inserisci il seguente codice:

void start();

Usa questo codice dopo aver sviluppato un oggetto thread e questo codice lo avvierà

  • Il tuo codice finito potrebbe assomigliare a questo

    class RunnableDemo implementa Runnable { thread privato t; stringa privata threadName; RunnableDemo(String name) { threadName = nome; System.out.println("Creazione " + threadName); } public void run() { System.out.println("In esecuzione " + threadName); try { for(int i = 4; i > 0; i--) { System.out.println("Thread: " + threadName + ", " + i); // Lascia riposare il thread per un po'. Thread.sleep(50); } } catch (InterruptedException e) { System.out.println("Thread " + threadName + " interrotto."); } System.out.println("Thread " + threadName + " in uscita."); } public void start() { System.out.println("Inizio " + threadName); if (t == null) { t = new Thread (this, threadName); t.start (); } } } public class TestThread { public static void main(String args) { RunnableDemo R1 = new RunnableDemo("Thread-1"); R1.start(); RunnableDemo R2 = new RunnableDemo("Thread-2"); R2.start(); } }

12477945 4
12477945 4

Passaggio 4. Esegui il codice

Se hai usato la codifica dell'esempio, l'output dovrebbe leggere

Creazione Discussione-1 Discussione iniziale-1 Creazione Discussione-2 Discussione iniziale-2 Discussione in esecuzione-1 Discussione: Discussione-1, 4 Discussione in esecuzione-2 Discussione: Discussione-2, 4 Discussione: Discussione-1, 3 Discussione: Discussione-2, 3 Thread: Thread-1, 2 Thread: Thread-2, 2 Thread: Thread-1, 1 Thread: Thread-2, 1 Thread Thread-1 in uscita. Thread Thread-2 in uscita.

Consigliato: