How to create new thread using Runnable in Java

1 Answer

0 votes
package javaapplication1;
 
public class JavaApplication1 implements Runnable{
    
    public void run() {

        for (int i = 0; i < 4; i++) {
            System.out.println("Child thread : " + i);
            try {
                Thread.sleep(30);
            } catch (InterruptedException ie) {
                System.out.println("Child thread error: " + ie);
            }
        }
        System.out.println("Child thread end ok");
    }
 
    public static void main(String[] args) {
 
        Thread t = new Thread(new JavaApplication1(), "My Thread");

        t.start();

        for (int i = 0; i < 6; i++) {

            System.out.println("Main thread : " + i);

            try {
                Thread.sleep(70);
            } catch (InterruptedException ie) {
                System.out.println("Main thread error: " + ie);
            }
        }
        System.out.println("Main thread end ok");
    }
}
 
/*

run:

Main thread : 0
Child thread : 0
Child thread : 1
Child thread : 2
Main thread : 1
Child thread : 3
Child thread end ok
Main thread : 2
Main thread : 3
Main thread : 4
Main thread : 5
Main thread end ok

*/

 



answered Oct 14, 2016 by avibootz
edited Oct 14, 2016 by avibootz

Related questions

1 answer 168 views
1 answer 184 views
1 answer 189 views
1 answer 161 views
1 answer 224 views
1 answer 207 views
...