Single thread is safe because there is only one thread, and there are no multiple threads that grab the same resource.
Code example:
public class SingleThread {int num=10;public void add(){while(num<13){num++;try{Thread.sleep(1000);}catch(Exception e){System.out.println("interrupt");}System.out.println(num);}}public static void main(String[] args){Thread thread = Thread.currentThread(); //Get the currently running thread object thread.setName("single thread"); //Thread rename System.out.println(thread.getName()+"Running");SingleThread st=new SingleThread();st.add();}}Multithreaded safety, synchronized synchronized code blocks
synchronized(object){}; //Synchronized code block
synchronized return value method name(){}; //Synchronized method
class One { int num=10; public void add(){ synchronized(this){ //Sync code blocks, synchronization method can also achieve the effect synchronized void add(){};num++; try { Thread.sleep(1000); } catch (InterruptedException e) { System.out.println("Interrupted"); } System.out.println(num); } }}class Two implements Runnable{ One one = new One(); @Override public void run() { one.add(); //Calling the add method}}public class Synch{ public static void main(String[] args) {Two two = new Two(); Thread t1 = new Thread(two); //Create three child threads Thread t2 = new Thread(two); Thread t3 = new Thread(two); t1.start(); t2.start(); t3.start(); }}Note: Observe the difference in running results of removing synchronized keywords!
Normal operation results:
11
12
13