1. Make sure which code is multithreaded.
2. Clear data sharing.
3. Make clear which statements in multithreaded running code are used to operate and share data.
synchronized is put on the function as a modifier.
The lock used by the synchronization function is: this
Verification: open two threads, one synchronization code block and one synchronization function.
class Ticket implements Runnable { private int tick = 100; boolean flag = true; @Override public void run() { if (flag) { while (true) { synchronized (this) { if (tick > 0) { try { Thread.sleep(10); } catch (InterruptedException e) { } System.out.println(Thread.currentThread().getName() + "...code:" + tick--); } } } }else while (true) show(); } public synchronized void show() { if (tick > 0) { try { Thread.sleep(10); } catch (InterruptedException e) { } System.out.println(Thread.currentThread().getName() + "...show():" + tick--); } } } public class Demo { public static void main(String[] args) { Ticket t = new Ticket(); Thread t1 = new Thread(t); Thread t2 = new Thread(t); t1.start(); try { Thread.sleep(10); }catch (InterruptedException e){ } t.flag=false; t2.start(); } }
this can ensure the normal operation of the program.
This points to the current object, but what if it is static? When it is static, there is no object created and this does not exist. What is the lock in the static function? Bytecode file object: class name.class
class Ticket implements Runnable { private static int tick = 100; boolean flag = true; @Override public void run() { if (flag) { while (true) { synchronized (Ticket.class) { if (tick > 0) { try { Thread.sleep(10); } catch (InterruptedException e) { } System.out.println(Thread.currentThread().getName() + "...code:" + tick--); } } } }else while (true) show(); } public static synchronized void show() { if (tick > 0) { try { Thread.sleep(10); } catch (InterruptedException e) { } System.out.println(Thread.currentThread().getName() + "...show():" + tick--); } } } public class Demo { public static void main(String[] args) { Ticket t = new Ticket(); Thread t1 = new Thread(t); Thread t2 = new Thread(t); t1.start(); try { Thread.sleep(10); }catch (InterruptedException e){ } t.flag=false; t2.start(); } }