// SimpleThread.java public class SimpleThread extends Thread { public SimpleThread(String str) { super(str); } public void run() { for (int i = 0; i < 30; i++) { System.out.println(i + " " + getName()); try { sleep((long)(Math.random() * 1000)); } catch (InterruptedException e) {} } System.out.println("Terminé! " + getName()); } }
// MainST.java public class MainST{ public static void main(String[] args){ SimpleThread un=new SimpleThread("un"); new SimpleThread("deux").start(); new SimpleThread("trois").start(); un.start(); try { un.join(); } catch (Exception e) { e.printStackTrace(); } System.out.println("l'activité un est finie"); } }
Implémenter Runnable :
On utilise ensuite une instanciation avec un constructeur de Thread ayant un constructeur de la classe (avec éventuellement d'autres arguments).
public class SimpleRunnable implements Runnable { public void run() { // ... } } // .... Thread tr = new Thread(new SimpleRunnable, "un"); tr.start(); // ...