I'm new at Concurrency, i'm trying to understand synchronized block:
public static int count1 = 0;
public static Object lock1 = new Object();
public static void add(){
synchronized (lock1) {
count1++;
}
}
my problem is with lock1, it doesn't work, when the method starts printing the color, it prints them randomly, so i think the problem is in synchronized block, because i watch some tutorials about this, all of them say the lock object must be static so no interference happens, but here i don't see that, Why?
This is the method that prints the color of each thread:
public static void compute(){
String color = null;
switch (Thread.currentThread().getName()) {
case "First Count Down":
color = TextColors.ANSI_YELLOW;
break;
case "Second Count Down":
color = TextColors.ANSI_MAGENTA;
break;
}
for (int i=0;i<100;i++) {
System.out.println(color + Thread.currentThread().getName() + "is Running");
//add();
add();
}
}
and this is the threads :
public static void main(String[] args) {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
compute();
}
});
t1.setName("First Count Down");
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
compute();
}
});
t2.setName("Second Count Down");
t1.start();
t2.start();
try{
t1.join();
t2.join();
}catch (InterruptedException io){
io.printStackTrace();
}
System.out.println("Count1 = " + count1 + " Count2 = " + count2);
}
Sorry if my English is bad, i'm not a native speaker, thanks in advance