This are my two classes:
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Main { public static int number = 0; public static void main(String...args) { ExecutorService pool = Executors.newFixedThreadPool(3); while (number < 51) { for (int i = 0; i < 3; i++) pool.execute(new Counter(i)); } pool.shutdown(); } } class Counter implements Runnable { private int number; public Counter(int number) { this.number = number; } @Override public void run() { synchronized (Main.class) { if (Main.number < 51) { System.out.println("Thread "+ number +":"+ Main.number); Main.number++; } } } }
So this program will run and count from 0 to 50 by using three different threads. Is my code thread safe? Is there any better way how to write my code?