标签:同步 ticket 使用 read while closed port logs close
import java.text.SimpleDateFormat; import java.util.*; import java.util.stream.Collectors; /** * Created by meicai on 2017/3/17. */ public class Hello { public static void main(String [] args) { Ticket ticket=new Ticket(); Thread t1=new Thread(ticket); Thread t2=new Thread(ticket); t1.start(); t2.start(); } } class Ticket implements Runnable{ private int num=10; @Override public void run() { sale(); } public void sale(){ while(num>0){ try { Thread.sleep(10); System.out.println("卖第"+num+"张票"+Thread.currentThread().getName()); num--; } catch (InterruptedException e) { e.printStackTrace(); } } } }
如图第6张票被不同的线程卖了,这样就出问题了。
import java.text.SimpleDateFormat; import java.util.*; import java.util.stream.Collectors; /** * Created by meicai on 2017/3/17. */ public class Hello { public static void main(String [] args) { Runnable r=new Ticket(); Thread t1=new Thread(r); Thread t2=new Thread(r); t1.start(); t2.start(); } } class Ticket implements Runnable{ Object obj=new Object(); private int num=500; @Override public void run() { sale(); } public void sale(){ //使用同步代码块来防止出现安全问题 synchronized (obj) { while (num > 0) { try { Thread.sleep(10); System.out.println("卖第" + num-- + "张票" + Thread.currentThread().getName()); } catch (InterruptedException e) { e.printStackTrace(); } } } } }
同步代码块保证了线程安全,效率低下,(使用了加锁机制)
标签:同步 ticket 使用 read while closed port logs close
原文地址:http://www.cnblogs.com/caohuimingfa/p/7644594.html