class TicketThread implements Runnable{ int tickets=100; public void run(){ while(true){ synchronized(this){ if(tickets>0){ try{ Thread.sleep(100); } catch(Exception e){ e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+":"+tickets--); } } } } } public class Solution{ public static void main(String[] args){ TicketThread tt=new TicketThread(); new Thread(tt,"Thread 1").start(); new Thread(tt,"Thread 2").start(); new Thread(tt,"Thread 3").start(); new Thread(tt,"Thread 4").start(); } }
实现线程间交替卖票(实际上也是两个线程交替打印奇偶数)
class TicketThread implements Runnable{ int tickets=100; public void run(){ while(true){ synchronized(this){ if(tickets>0){ notify(); try{ Thread.sleep(100); } catch(Exception e){ e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+":"+tickets--); try{ wait(); }catch(InterruptedException e){ e.printStackTrace(); } } } } } } public class Solution{ public static void main(String[] args){ TicketThread tt=new TicketThread(); new Thread(tt,"Thread 1").start(); new Thread(tt,"Thread 2").start(); //new Thread(tt,"Thread 3").start(); //new Thread(tt,"Thread 4").start(); } }
posted on
浙公网安备 33010602011771号