Hasholef
Hasholef

Reputation: 753

Java program is stuck on a specific thread

I'm trying to create 2 threads that both have infinite loop and should be switching from each other. The problem is that I'm getting stucked in the first thread forever and no context switch is being happend. What is my mistake? I'm using java8 and Eclipse Juno.

This is the 'Main' class:

public class Main {

    /**
     * @param args
     */
    public static void main(String[] args) 
    {

        test1 t = new test1();
        test2 t2 = new test2();
        t.run();
        t2.run();

        while(true)
        {
            System.out.println("text from main");
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }


    }

}

This is the 'test1' class:

public class test1 implements Runnable {

    public void run() 
    {
        while(true)
        {
            System.out.println("text from thread");
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

}

This is the 'test2' class:

public class test2 implements Runnable {

    public void run() 
    {
        while(true)
        {
            System.out.println("text from thread2");
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

}

Upvotes: 0

Views: 918

Answers (2)

Rajiv
Rajiv

Reputation: 21

Adding with previous answers: making an statement like

Thread t = new Thread(new test1()); t.run();

here you are simply calling the run method of the runnable object- (associated in the thread object initialization step,i.e. first statement). So, To start a new thread you must use t.start();

Upvotes: 0

PDani
PDani

Reputation: 735

The right thing to do would be

Thread t = new Thread(new test1());
Thread t2 = new Thread(new test2());
t.start();
t2.start();

Cheers, Daniel

Upvotes: 3

Related Questions