解決并發(fā)的同步方法的代碼
/*
?* 線程安全:在并發(fā)時保證數(shù)據(jù)的正確性,同時保證效率盡可能高
?* synchronized
?* 1.同步方法(在方法上面加synchronized)
?* 2.同步塊
?*/
public class SynTest01 {
?? ?public static void main(String[] args) {
?? ??? ?//一份資源
?? ??? ?SafeWeb12306? web=new SafeWeb12306();
?? ??? ??? ??? ?//多個代理
?? ??? ??? ??? ?new Thread(web,"laoda").start();
?? ??? ??? ??? ?new Thread(web,"laoer").start();
?? ??? ??? ??? ?new Thread(web,"laosan").start();
?? ?}
}
class SafeWeb12306 implements Runnable{
?? ?//票數(shù)
?? ?private int ticketNums=3;
?? ?private boolean flag=true;
?? ?@Override
?? ?public void run() {
?? ??? ?while(flag) {
?? ??? ??? ?test();
?? ??? ?}
?? ??? ?
?? ?}
?? ?//線程安全,同步
?? ?public synchronized void test() {
?? ??? ?if(ticketNums<0) {
?? ??? ??? ?flag=false;
?? ??? ??? ?return;
?? ??? ?}
?? ??? ?//模擬網(wǎng)絡延時
?? ??? ?try {
?? ??? ??? ?Thread.sleep(200); ?
?? ??? ??? ?//進入了阻塞狀態(tài),然后200s以后我就重新等待CPU的調用
?? ??? ??? ?//繼續(xù)執(zhí)行下面的代碼
?? ??? ?} catch (InterruptedException e) {
?? ??? ??? ?e.printStackTrace();
?? ??? ?}
?? ??? ?System.out.println(Thread.currentThread().getName()+"-->"+ticketNums--);
?? ?}
?? ?
}
標簽: