Thread 线程同步

来源:互联网 发布:天网塞班软件站 编辑:程序博客网 时间:2024/04/30 07:47
package com.ppa.thread;class TicketRunable implements Runnable {    private int ticket = 5;    @Override    public void run() {        for (int i = 0; i < 10; i++) {        //同步代码块//          synchronized (this) {//              if (ticket > 0) {//                  ticket--;//                  try {//                      Thread.sleep(500);//                  } catch (InterruptedException e) {//                      // TODO Auto-generated catch block//                      e.printStackTrace();//                  }//                  System.out.println("剩余车票:"+ticket);//              }//          }            sell();  //车票售卖:所有的线程使用唯一的票源        }    }    //同步方法    private synchronized void sell() {        if (ticket > 0) {            ticket--;            try {                Thread.sleep(500);            } catch (InterruptedException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }            System.out.println("剩余车票:"+ticket);        }           }}public class SynThreadDemo {    public static void main(String[] args) {       TicketRunable runable = new TicketRunable();       Thread t1 = new Thread(runable);       Thread t2 = new Thread(runable);       Thread t3 = new Thread(runable);       t1.start();       t2.start();       t3.start();    }}