satya
satya

Reputation: 33

Print ArrayList sequentially using two threads in Java

How below code is an example of bad coding and how can we improve it? please help me understanding it.

Problem : Print ArrayList Sequentially using two threads

My Code : -

public class xyz {

    public static void main(String[] args) throws InterruptedException {

        ArrayList<Integer> list1 = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));

        Thread odd = new Thread(() -> {
            for (int i = 0; i < list1.size(); i = i + 2) {
                synchronized (list1) {
                    System.out.println(Thread.currentThread().getName() + "  : " + list1.get(i));
                    list1.notifyAll();
                    try {
                        list1.wait();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        });

        Thread even = new Thread(() -> {
            for (int i = 1; i < list1.size(); i = i + 2) {
                synchronized (list1) {
                    System.out.println(Thread.currentThread().getName() + " : " + list1.get(i));
                    list1.notifyAll();
                    try {
                        list1.wait();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        });

        odd.setName("Odd");
        even.setName("Even");

        odd.start();
        even.start();

        odd.join();
        even.join();
    }
}

RESULT -

Odd : 1 Even : 2 Odd : 3 Even : 4 Odd : 5 Even : 6 Odd : 7 Even : 8 Odd : 9 Even : 10

Upvotes: 0

Views: 256

Answers (1)

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147154

It's bad coding because it is using multiple threads to do something sequentially... That aside.

The thing that pops out is that wait is not in a while loop. Always (almost) put wait in a while loop. There's probably good references for that if you have a google - I'd still go for Doug Lea's Concurrent Programming In Java 2nd Ed from the last century.

There's probably a better way of doing this with java.util.concurrent - see Java Concurrency In Practice.

You will need some kind of shared state to indicate which thread should be executing. Check that in your while condition.

I notice that it is calling size from outside the lock. While this may be okay, it is a non-thread safe mutable object that you are calling.

What is truly terrible is that most of the code is duplicated.

Upvotes: 2

Related Questions