W poniższym fragmencie kodu zadeklarowanie metody doThings() jako statycznej spowodowałoby, że klasa będzie bezpieczna dla wątków. Czy powodem jest to, że jeśli wiele wątków TestSeven zostanie uruchomionych, a x jest zmienną statyczną, to może wystąpić warunek wyścigu?Dlaczego ten kod nie jest bezpieczny dla wątków?
public class TestSeven extends Thread{
private static int x;
public synchronized void doThings(){
int current = x;
current++;
x = current;
}
public void run(){
doThings();
}
public static void main(String args[]){
TestSeven t = new TestSeven();
Thread thread = new Thread(t);
thread.start();
}
}
Przekaż testeeven, który jest wątkiem jako argument konstruktora wątków. Działa to, ponieważ wątek IS-A może zostać uruchomiony, ale nie jest zalecany, lepiej wykonać TestSeven implementuj Runnable –