当多个线程并发访问同一个资源对象时,可能会出现线程不安全的问题
public class Method implements Runnable { private static int num=50; public void run() { for(int i=0;i<50;i++){ eat(); } } synchronized private void eat(){ if(num>0){ System.out.println(Thread.currentThread().getName()+"吃了编号为"+num+"的苹果!"); try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } num--; } } public static void main(String[] args) { Thread t=new Thread(); Method a=new Method(); new Thread(a,"小A").start(); new Thread(a,"小B").start(); new Thread(a,"小C").start(); } }
public class Method_1 implements Runnable { private static int num = 50; public void run() { for (int i = 0; i < 50; i++) { synchronized (this) { if (num > 0) { System.out.println(Thread.currentThread().getName() + "吃了编号为" + num + "的苹果!"); try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } num--; } } } } public static void main(String[] args) { Method_1 m = new Method_1(); new Thread(m, "小A").start(); ; new Thread(m, "小B").start(); ; new Thread(m, "小C").start(); ; } }