-2

I'm playing around with threads in Java for the first time and I'm just trying to convince myself they do what I think they are doing.

I expect the following code to run two loops at the same time, therefore I'm expecting the output to be some a mix of the counters. However, every time I run the code I get a straight count from 1 to 3000 with all the numbers in sequence.

Am I missing something? Is there a better way to demonstrate two threads actually working at the same time?

public class ThreadDemo {

public static void main(String[] args) {
    Loop1 loop1 = new Loop1();
    Loop2 loop2 = new Loop2();

    loop1.run();
    loop2.run();
}


public static class Loop1 implements Runnable {
@Override
public void run() {
    for(int i= 1; i <= 1000; i++){
        System.out.println(i);
    }
}


public static class Loop2 implements Runnable {
@Override
public void run() {
    for(int i= 2000; i <= 3000; i++){
        System.out.println(i);
    }
}
}
  • Your question is on most basic threading, and much better to search for and read a tutorial on this first before coming here. You can find the main Java tutorials here: [The Really Big Index](http://docs.oracle.com/javase/tutorial/reallybigindex.html). Please save this link and refer to it frequently. I know that I do. – Hovercraft Full Of Eels Jun 17 '18 at 20:07

2 Answers2

0

To execute a thread, you need to use the start() method. When you call run() it is just an standard method call on the same thread that calls it.

You should also try to call join() on your threads at the end.

Dragonthoughts
  • 2,180
  • 8
  • 25
  • 28
0

A Runnable is not a Thread. You need

Thread t = new Thread(loop1);
t.start();
Yuri Schimke
  • 12,435
  • 3
  • 35
  • 69