用卖票演示多线程:
1 package javase; 2 3 class Ticket implements Runnable{ 4 5 private int num = 300; 6 7 Object obj = new Object(); 8 9 public void run() { 10 11 show(); 12 } 13 14 public void show() { 15 16 synchronized (obj) { 17 18 while(num>0) { 19 20 try { 21 Thread.sleep(10); 22 } catch (InterruptedException e) { 23 e.printStackTrace(); 24 } 25 26 System.out.println(Thread.currentThread().getName()+" ticket="+num--); 27 } 28 } 29 30 } 31 32 } 33 34 public class ThreadDemo2 { 35 36 public static void main(String[] args) { 37 38 Ticket t = new Ticket(); 39 Thread t1 = new Thread(t); 40 Thread t2 = new Thread(t); 41 Thread t3 = new Thread(t); 42 43 t1.start(); 44 t2.start(); 45 t3.start(); 46 47 } 48 49 }
创建三个线程对一个对象执行任务,即共用一个数据域。在执行 while(num>0)语句时,假设此时num=1,线程1进入并暂停运行。而此时num=1,线程2进入执行 num--,使得num=0输出打印。当线程1执行时,已经通过while语句的判断了,直接执行 num-- 输出打印,从而打印了0,出现错误。
使用线程同步块,在synchronized语句中只有一个线程进入,此时synchronized会给出判断结果,阻挡其他线程进入synchronized下的代码块,也就使得while语句每次都能执行完,避免错误。
原文:https://www.cnblogs.com/lsy-lsy/p/10907408.html