java多线程中的 锁(暂时记录)
P150-lock----锁----那一节
public class ThreadExtend extends Thread {
static int ticket = 0;
static Lock lock = new ReentrantLock();
public void run() {
while (true) {
lock.lock();
if (ticket == 100) {
break;
} else {
try {
Thread.sleep(30);
ticket++;
System.out.println(Thread.currentThread().getName() + "卖票" + ticket);
} catch (Exception e) {
} finally {
lock.unlock();
}
}
}
}
}
---分割线---对比--
public class ThreadExtend extends Thread {
static int ticket = 0;
static Lock lock = new ReentrantLock();
public void run() {
while (true) {
lock.lock();
if (ticket == 100) {
break;
} else {
try {
Thread.sleep(30);
} catch (Exception e) {
} finally {
lock.unlock();
}
ticket++;
System.out.println(Thread.currentThread().getName() + "卖票" + ticket);
}
}
}
}
----------********-----------
ticket++;
sout();
换个位置。结果完全不一样。这是不是说明 就算加锁, try里面的语句会全部执行完毕呢? 这种随机性,不会跨越try括号里的整体???