* 1. 用synchronized(任意标记){要同步的代码}
* 2. 定义一个synchronized方法 ,把要同步的代码装进代码块里 public synchronized void m1() {}
* 3. 创建ReentrantLock rl = new ReentrantLock();进入锁
* (1) rl.lock(); //加锁 要加要锁的地方
* (2) rl.unlock(); //解锁
* (3) lock 可以提高效率,当判断被锁住是,就会进入休眠状态,把cpu时间让出来,
* (4) 灵活,在哪里锁就在那里放
public class Lock111 {
public static void main(String[] args) {
// Method11 method11 = new Method11();
// Method22 method11 = new Method22();
Method333 method11 = new Method333();
Thread thread = new Thread(method11);
Thread thread1 = new Thread(method11);
thread.start();
thread1.start();
}
}
class Method11 implements Runnable {
private int date = 20; //数据,总共有20张票数
@Override
public void run() {
for (int i = 0; i < 10; i++) {
synchronized (this) {
if (date > 0) { //当票数是整数的时候就打印输出
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " >>>票剩余>>>" + (date--));// date可以先减,也可以在这里减
}
}
}
}
}
class Method22 implements Runnable {
private int date = 20;
@Override
public void run() {
m1();
}
public synchronized void m1() {
for (;;) {
if (date > 0) {
System.out.println(Thread.currentThread().getName() + " <<<>>>" + (date--));
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
class Method333 implements Runnable {
private int date = 20;
ReentrantLock rl = new ReentrantLock();
@Override
public void run() {
for (;;) { //死循环
rl.lock();
if (date > 0) {
System.out.println(Thread.currentThread().getName() + " <<<<>>>>" + (date--));
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
rl.lock();
}
}
}