- Za każdym razem zwraca mi 30000 i takiej wartości sie spodziewałam. ( uruchomione 3 watki, każdy zwiększa licznik o 10000 )
2. Przetestuj rozwiązania z synchronizacją w metodzie run() i z synchronizacją w metodzie increment(). Które rozwiązanie jest lepsze?
- nie widze zadnej roznicy odkomentujac synchronizacje w tych metodach.
Dopiero sie ucze, dużo się już naczytałam o synchronizacji i wydaje mi sie ze rozumiem na czym polega ale z odpowiedzią na te pytania mam straszny problem. Będe bardzo wdzięczna za jakąkolwiek pomoc.
Kod: Zaznacz cały
public class WatkiSynch{
public static void main(String args[]) throws InterruptedException{
IncCounter cc = new IncCounter(0);
Thread thread1 = new Thread(new IncrementCounterThread(cc));
Thread thread2 = new Thread(new IncrementCounterThread(cc));
Thread thread3 = new Thread(new IncrementCounterThread(cc));
thread1.start();
thread2.start();
thread3.start();
Thread.sleep(5000);
System.out.println("Wartość licznika: " + cc.getCounter());
}
}
class IncCounter{
private int value;
public IncCounter(int StartValue)
{
this.value = StartValue;
}
//public synchronized void increment()
public void increment()
{
value++;
}
public int getCounter()
{
return value;
}
}
class IncrementCounterThread implements Runnable{
IncCounter counter;
public IncrementCounterThread(IncCounter counter)
{
this.counter = counter;
}
public void run()
{
for(int i = 0; i < 10000; i++){
//synchronized(counter){
counter.increment();
//}
}
}
}