Lock
- 是什么
参考java8API

Lock implementations provide more extensive locking operations than can be obtained using synchronized methods and statements. They allow more flexible structuring, may have quite different properties, and may support multiple associated Condition objects.
Lock实现提供更广泛的锁定操作可以比使用 synchronized获得方法和声明更好。他们允许更灵活的结构,可以有完全不同的特性,可以支持多个相关的 Condition对象。
java培训教程Lock接口
- Lock接口的实现
ReentrantLock可重入锁,参考Java8API

- 创建线程方式
- 继承Thread
例如:
public class SaleTicket extends Thread
Java是单继承,资源宝贵,要用接口方式
- new Thread()
例如:
Thread t1 = new Thread();
t1.start();
不能这样实现
- Thread(Runnable target, String name)
参考Java8API


- 实现线程方法
- 新建类实现runnable接口
class MyThread implements Runnable//新建类实现runnable接口
new Thread(new MyThread,…)
这种方法会新增类,有更新更好的方法
- 匿名内部类
new Thread(new Runnable() {
@Override
public void run() {
}
}, “your thread name”).start();
这种方法不需要创建新的类,可以new接口
- lambda表达式
new Thread(() -> {
}, “your thread name”).start();
这种方法代码更简洁精炼
- 程序代码
package com.atguigu.thread;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class Ticket //实例例eld +method
{
private int number=30;
// Lock implementations provide more extensive locking operations
// than can be obtained using synchronized methods and statements.
private Lock lock = new ReentrantLock();//List list = new ArrayList()
public void sale()
{
lock.lock();
try {
if(number > 0) {
System.out.println(Thread.currentThread().getName()+”卖出”+(number–)+”\t 还剩number);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
}
}
相关: 深圳前端培训机构哪家比较好——深圳跨专业学习Java可以吗