publicclassTestimplementsRunnable{privateint count =10;boolean flag =true;@Overridepublicvoidrun(){while(flag){getbuy();}}//当前锁住的是Test对象,所以后面线程都排队进来publicsynchronizedvoidgetbuy(){if(count <=0){
flag =false;return;}try{
Thread.sleep(200);}catch(InterruptedException e){
e.printStackTrace();}
System.out.println("当前线程为"+Thread.currentThread().getName()+"抢到第"+count--+"张票");}publicstaticvoidmain(String[] args){
Test test =newTest();newThread(test,"小米").start();newThread(test,"小黑").start();newThread(test,"小黄").start();}}
代码块(锁的对象就是变化的量,需要增删改)
publicclassListTest{publicstaticvoidmain(String[] args)throws InterruptedException {
List<String> list =newArrayList<>();for(int i =0; i <10000; i++){newThread(()->{//锁的对象就是变化的量,需要增删改synchronized(list){
list.add(Thread.currentThread().getName());}}).start();}
Thread.sleep(300);
System.out.println(list.size());}}
Lock锁
publicclassTest2implementsRunnable{privateint count =10;boolean flag =true;privatefinal ReentrantLock lock =newReentrantLock();@Overridepublicvoidrun(){while(flag){try{//加锁
lock.lock();getbuy();}finally{//释放锁
lock.unlock();}}}publicvoidgetbuy(){if(count <=0){
flag =false;return;}try{
Thread.sleep(200);}catch(InterruptedException e){
e.printStackTrace();}
System.out.println("当前线程为"+Thread.currentThread().getName()+"抢到第"+count--+"张票");}publicstaticvoidmain(String[] args){
Test2 test =newTest2();newThread(test,"小米").start();newThread(test,"小黑").start();newThread(test,"小黄").start();}}