multithreading synchronized for loop

I am trying to write a multithreaded program that runs two threads. The two threads execute a for loop together and print out numbers 0 to 99. The problem I am having is each thread runs the for loop 0 to 99, so I get 0 to 99 twice instead of them working together to get to 99.

My results look like this

1
1
2
2
3
3

I want something like this, where each thread prints a number all the way to 100.

1
2
3
4
all the way to 100 then stop

What am I doing wrong?

This is my code

public class JavaApplication220 implements Runnable {

    public int i;

    public void run() {
        synchronized (this) {
            for (i = 0; i < 100; i++) {
                System.out.println(i);
                try {
                    Thread.sleep(1);
                } catch (InterruptedException ex) {
                    Logger.getLogger(JavaApplication220.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
}

This is the main() class

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class NewClass {
    public static void main(String[] args) {
        JavaApplication220 thread1 = new JavaApplication220();
        JavaApplication220 thread2 = new JavaApplication220();

        ExecutorService executor = Executors.newCachedThreadPool();
        executor.execute(thread1);
        executor.execute(thread2);

        executor.shutdown();
    }
}

Answer

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

public class Test {
    public static void main(String args[]){


        AtomicInteger i = new AtomicInteger(0);
        i.set(0);
        TestingT thread1 = new TestingT(i);
        TestingT thread2 = new TestingT(i);

        ExecutorService executor = Executors.newCachedThreadPool();
        executor.execute( thread1 );
        executor.execute( thread2 );

        executor.shutdown();
    }
}
class TestingT implements Runnable {
    AtomicInteger i;
    TestingT(AtomicInteger i ){
        this.i = i;
    }
    @Override
    public void run(){
        while(this.i.get() < 100) {
            int i = this.i.incrementAndGet();
            System.out.println(Thread.currentThread().getName()+" "+i);
        }
    }
}

this should works fine with your requirements

Leave a Reply

Your email address will not be published. Required fields are marked *