线程的同步 The code segments within a program that access the same object from separate, concurrent threads are called “critical sections”。 同步的两种方式:同步块和同步方法 每一个对象都有一个监视器,或者叫做锁。 同步方法利用的是this所代表的对象的锁。 每个class也有一个锁,是这个class所对应的Class对象的锁。
class TicketsSystem ...{ publicstaticvoid 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=100; publicvoid run() ...{ while(true) ...{ if(tickets>0) /** *//**假设第一个线程进入IF语句中,时间片刚好到期,然后第二个线程运行,进入IF语句中 时间片刚好到期,然后第三个线程运行,进入IF语句中,时间片刚好到期 然后第四个线程运行,进入IF语句中,时间片刚好到期.之后,第一个线程获得时间片, 开始运行语句,开始减减,卖了1这张票,tickets变为0,第二个线程卖了0这张票, tickets变为-1.第三个线程卖了-1这张票,tickets变为-2,第四个线程卖了-2这张票,tickets变为-3, 让线程睡眠一下,可以捕捉结果*/ ...{ try ...{ Thread.sleep(1000); } catch(Exception e) ...{ e.printStackTrace(); } System.out.println("obj:"+Thread.currentThread().getName()+ " sell tickets:"+tickets); tickets--; } } } }
同步块:
class TicketsSystem1 ...{ publicstaticvoid 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=100; Object ojb=new Object();//这个可以是任意的对象 publicvoid run() ...{ while(true) ...{ synchronized(ojb) /** *//**(这是同步块)当第一个线程达到的时候,首先要判断下OJB的监视器是否加锁了 如果没有加的话,它就会给OJB这个对象加锁,然后往下执行,执行到SLEEP的时候,睡眠1秒 当第二个线程到达的时候,发现OJB这个对象已经加锁,它只能等待*/ ...{ if(tickets>0) /** *//**假设第一个线程进入IF语句中,时间片刚好到期,然后第二个线程运行,进入IF语句中 时间片刚好到期,然后第三个线程运行,进入IF语句中,时间片刚好到期 然后第四个线程运行,进入IF语句中,时间片刚好到期.之后,第一个线程获得时间片, 开始运行语句,开始减减,卖了1这张票,tickets变为0,第二个线程卖了0这张票, tickets变为-1.第三个线程卖了-1这张票,tickets变为-2,第四个线程卖了-2这张票,tickets变为-3, 让线程睡眠一下,可以捕捉结果*/ ...{ try ...{ Thread.sleep(1000); } catch(Exception e) ...{ e.printStackTrace(); } System.out.println("obj:"+Thread.currentThread().getName()+ " sell tickets:"+tickets); tickets--; } } } } }