Intro
This examples will demonstrates how to create a new thread. To create a thread, your java class must implements runnable interface.
Examples
package com.freesamplecode.java.thread; public class CreateNewThreadDemo implements Runnable { public static void main(String[] args){ //create new thread with names "Thread Demo"; Thread t = new Thread(new CreateNewThreadDemo(), "Thread Demo"); //start a thread t.start(); for(int i = 0; i < 5; i++){ System.out.println("Main thread : "+i); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("Main thread finished"); } @Override public void run() { for(int i = 0; i < 5; i++){ System.out.println("Child thread : "+i); try{ Thread.sleep(50); }catch(InterruptedException ex){ ex.printStackTrace(); } } System.out.println("Child thread finished "); } }
Output
Main thread : 0 Child thread : 0 Child thread : 1 Main thread : 1 Child thread : 2 Child thread : 3 Main thread : 2 Child thread : 4 Child thread finished Main thread : 3 Main thread : 4 Main thread finished
0 comments: