Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,870 questions

51,793 answers

573 users

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 155 views
1 answer 174 views
1 answer 156 views
1 answer 139 views
1 answer 184 views
1 answer 191 views
...