- 线程的创建方式和停止
继承Thread 实现run方法
实现Runnable接口, 作为new Thread()的构造器参数
当jvm进程中的所有前台线程退出了, 后台线程也就自动退出了.
t1.setDaemon(true)–>后台线程
t1.setDaemon(false)–>前台线程 默认是前台线程. - 线程通信
synchronized(object){
object.wait(); //等待其他线程调用object.notify().
object.notify(); //通知object.wait()的线程继续执行.
}
生产者和消费者模型:
生产者:
syncthronized(monitor){
while(货架不为空){
monitor.wait(); //等待货架上的货物消费完.
}
生产商品,放到货架上.
monitor.nonifyAll(); //通知消费者来取货
}
消费者:
synchronized(monitor){
while(货架为空){ //当消费者取走货物后, 调用notifyAll,不仅通知了生产者,也通知了其他消费者.造成有货物的假象. 所以由if改为while
monitor.wait(); //等待生产者生产货物并放到货架上.
}
取走货物
monitor.notifyAll(); //通知生产者没有货物了
}
JDK API中 Condition章节提供的示例。
class BoundedBuffer {
final Lock lock = new ReentrantLock();
final Condition notFull = lock.newCondition();
final Condition notEmpty = lock.newCondition();
final Object[] items = new Object[100];
int putptr, takeptr, count;
public void put(Object x) throws InterruptedException {
lock.lock();
try {
while (count == items.length)
notFull.await();
items[putptr] = x;
if (++putptr == items.length) putptr = 0;
++count;
notEmpty.signal();
} finally {
lock.unlock();
}
}
public Object take() throws InterruptedException {
lock.lock();
try {
while (count == 0)
notEmpty.await();
Object x = items[takeptr];
if (++takeptr == items.length) takeptr = 0;
--count;
notFull.signal();
return x;
} finally {
lock.unlock();
}
}
}
- 线程同步
1). synchronized(监听对象);
2). Lock锁用例Lock lock = new ReentryLock(); try{ xxxxxx lock.lock(); }finally{ lock.unlock(); }
随时随地看视频