publicstaticvoidmain(String[] args){ final ClhSpinLock lock = new ClhSpinLock(); lock.lock(); for(int i = 0; i < 10; i++){ new Thread(new Runnable(){ @Override publicvoidrun(){ lock.lock(); SleepUtils.mills(10); lock.unlock(); } },"Thread"+i).start();
} lock.unlock(); }
}
执行后输出结果为: main waiting for lock main get the lock Thread0 waiting for lock Thread3 waiting for lock Thread1 waiting for lock Thread4 waiting for lock Thread2 waiting for lock Thread7 waiting for lock main releases the lock. Thread0 get the lock Thread8 waiting for lock Thread5 waiting for lock Thread0 releases the lock. Thread9 waiting for lock Thread6 waiting for lock Thread3 get the lock Thread3 releases the lock. Thread1 get the lock Thread1 releases the lock. Thread4 get the lock Thread4 releases the lock. Thread2 get the lock Thread7 get the lock Thread2 releases the lock. Thread7 releases the lock. Thread8 get the lock Thread5 get the lock Thread8 releases the lock. Thread5 releases the lock. Thread9 get the lock Thread6 get the lock Thread9 releases the lock. Thread6 releases the lock.
publicstaticvoidmain(String[] args){ final ClhSpinLock lock = new ClhSpinLock(); lock.lock(); for(int i = 0; i < 10; i++){ new Thread(new Runnable(){ @Override publicvoidrun(){ lock.lock(); SleepUtils.mills(10); lock.unlock(); } },"Thread"+i).start();
} lock.unlock(); }
}
执行后输出结果为: main waiting for lock main get the lock Thread0 waiting for lock Thread3 waiting for lock Thread1 waiting for lock Thread4 waiting for lock Thread2 waiting for lock Thread7 waiting for lock main releases the lock. Thread0 get the lock Thread8 waiting for lock Thread5 waiting for lock Thread0 releases the lock. Thread9 waiting for lock Thread6 waiting for lock Thread3 get the lock Thread3 releases the lock. Thread1 get the lock Thread1 releases the lock. Thread4 get the lock Thread4 releases the lock. Thread2 get the lock Thread7 get the lock Thread2 releases the lock. Thread7 releases the lock. Thread8 get the lock Thread5 get the lock Thread8 releases the lock. Thread5 releases the lock. Thread9 get the lock Thread6 get the lock Thread9 releases the lock. Thread6 releases the lock.