I'm new to the multi-threading concept and I'm creating a simple Java program to experience with multiple threads and stuff.
In my program, I simply have a linked list, and I create a thread to just remove list items from the beginning. I implement the Runnable interface and this is what the run method of my thread looks like: (I set list in the constructor)
public void run() {
System.out.println("Starting...");
while (!list.isEmpty()) {
synchronized (list) {
list.removeFirst();
}
}
System.out.println("Finished!");
}
In the main method, I add a huge number of items to the linked list (10,000,000) and simply create instances of this class to run concurrently and I measure the time:
Thread my1 = new Thread(new MyThread("my1", list));
Thread my2 = new Thread(new MyThread("my2", list));
Thread my3 = new Thread(new MyThread("my3", list));
startTime = System.currentTimeMillis();
my1.start();
my2.start();
my3.start();
my1.join();
my2.join();
my3.join();
endTime = System.currentTimeMillis();
elapsedTime = endTime - startTime;
System.out.println("Main finished in " + elapsedTime + " milliseconds.");
Interestingly enough, when I run my program using these 3 threads, I receive the message:
Main finished in 444 milliseconds
But, when I use only a single thread, I receive the message:
Main finished in 223 milliseconds
Is there anyway I can tweak the code to run actually faster when using multiple threads???
Thank you in advance
list = null;why do you want to remove elements one by one if your purpose is to remove all fasterlist.empty()test outside of the synch block is not thread-safe.