Reputation: 121
I am trying to count 100 numbers by multi-threading and single-threading. Since synchronized keyword allows only one thread at a time (it is kind of like a single thread), so these two methods below should have the same runtime approximately if we ignore the effect of time consuming of creating and synchronizing threads?
Multi-threading using synchronized:
public synchronized static void increment() {
sum++;
}
public static void main(String[] args) {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 50; i++) {
increment();
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 50; i++) {
increment();
}
}
});
t1.start();;
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(sum);
Single-threading:
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
sum++
}
System.out.println(sum);
}
Upvotes: 1
Views: 828
Reputation: 84
Java is really good at multithreading, but there is a lot of overhead with creating and synchronizing threads, so don't be surprised if, for a simple problem like counting to 100, you actually see an increase in runtime.
Upvotes: 1