未上锁
package senior;
public class TestLock {
public static void main(String[] args) {
TestLock1 testLock1 = new TestLock1();
new Thread(testLock1).start();
new Thread(testLock1).start();
new Thread(testLock1).start();
}
}
class TestLock1 implements Runnable{
private int ticketNums=10;
//static final ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
while (true) {
if (ticketNums>0) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(ticketNums--);
}else {
break;
}
}
}
}
10
8
9
7
6
7
5
5
5
4
3
4
2
2
2
1
1
1
上锁后
package senior;
import java.util.concurrent.locks.ReentrantLock;
public class TestLock {
public static void main(String[] args) {
TestLock1 testLock1 = new TestLock1();
new Thread(testLock1).start();
new Thread(testLock1).start();
new Thread(testLock1).start();
}
}
class TestLock1 implements Runnable{
private int ticketNums=10;
static final ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
while (true) {
try {
lock.lock();
if (ticketNums>0) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(ticketNums--);
}else {
break;
}
} finally {
lock.unlock();
}
}
}
}
10
9
8
7
6
5
4
3
2
1