线程不同步时class SellThread implements Runnable{ int tickets=10;//总票数public void run(){while(true){ if(tickets>0){ try{ Thread.sleep(10); //当前正在执行线程睡眠一会}catch(Exception e){ e.printStackTrace();}System.out.println (Thread.currentThread ().getName ()+"Selltickets:"+tickets);tickets-- ;}} } }public class Ticket {//主类public static void main(String args[ ]){ SellThread st=new SellThread();new Thread(st). start(); new Thread(st). start();new Thread(st). start(); new Thread(st). start();}}方法级线程同步class SellThread implements Runnable{ int tickets=10;//总票数public void run(){while(true){ this.sell();} }public synchronized void sell(){//同步方法if(tickets>0){ try{ Thread.sleep(10); //当前正在执行线程睡眠一会}catch(Exception e){ e.printStackTrace();}System.out.println (Thread.currentThread ().getName ()+"Selltickets:"+tickets);tickets-- ;}}}public class Ticket {//主类public static void main(String args[ ]){ SellThread st=new SellThread();new Thread(st). start(); new Thread(st). start();new Thread(st). start(); new Thread(st). start();}}对象级线程同步class SellThread1 implements Runnable{ int tickets=10;//总票数public void run(){while(true){ synchronized(this){if(tickets>0){ try{ Thread.sleep(10); //当前正在执行线程睡眠一会}catch(Exception e){ e.printStackTrace();}System.out.println (Thread.currentThread ().getName ()+"Selltickets:"+tickets);tickets-- ;}}} } }public class Ticket1 {//主类public static void main(String args[ ]){ SellThread1 st=new SellThread1();new Thread(st). start(); new Thread(st). start();new Thread(st). start(); new Thread(st). start();}}


