A safe thread means that if it is used simultaneously from several threads, it should not cause any problems.
Execution without static
public class TestSeven extends Thread { private static int x; public synchronized void doThings() { int current = x; current++; x = current; } public void run() { doThings(); } }
If you make an instance of TestSeven and call it run() , it will return the result as 1 each time. But wait x is static , so should you not increase the output by 1 every time you call it? Thus, this means that the method is not thread safe . To do this, we would:
Run with static
public class TestSeven extends Thread { private static int x; public static synchronized void doThings() { int current = x; current++; x = current; } public void run() { doThings(); } }
Remember synchronized is the "way" to make threads safe, but there are other ways.
See more details.
source share