一、等待和唤醒机制
1、等待机制
TimeWaiting有两种方式:单位是毫秒
sleep、wait
2、唤醒机制
notify:唤醒wait的单个线程
notifyAll:唤醒有wait的所有线程
3、注意:
1)、等待和唤醒线程必须在同步代码块中
2)、两个线程使用的锁对象必须同步一致
3)、等待和唤醒线程只能被锁对象调用
public static void main(String[] args) {
//这里首先创建锁对象
Object object = new Object();
//创建服务员线程
new Thread(){
@Override
public void run(){
//使用同步代码块传递锁对象
synchronized (object){
System.out.println("服务员:张厨师,农家小炒肉一份,醋溜土豆丝一份");
try {
//在锁对象中调用wait方法
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
//被notify唤醒后
System.out.println("服务员:好的,来了!");
}
}
}.start();
//创建厨师线程
//因为共用锁对象,不要创建锁对象
new Thread(){
@Override
public void run(){
//使用同步机制传递锁对象
synchronized (object){
try {
//厨师菜要做多久
Thread.sleep(200);//两秒钟
} catch (InterruptedException e) {
e.printStackTrace();
}
//锁对象调用notify方法
object.notify();
System.out.println("厨师:小二,一份农家小炒肉,一份醋溜土豆丝");
}
}
}.start();
}
/*
服务员:张厨师,农家小炒肉一份,醋溜土豆丝一份
厨师:小二,一份农家小炒肉,一份醋溜土豆丝
服务员:好的,来了!
*/
二、线程池
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;//线程池的工厂类
线程池的使用步骤:
1、使用 Executors 的静态方法 newFixedThreadPool 生产一个指定线程数量的线程池
2、创建一个实现Runnable的类,重写run方法,添加线程任务
3、调用ExecutorService中的方法:有两个
(1)、submit:传递实现类线程任务,执行 run 方法
(2)、shutdown:关闭线程池,一般不建议执行
public class runnable00 implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"创建一个线程");
}
}
public static void main(String[] args) {
//1.使用工厂类Executors的静态方法newFixedThreadPool创建线程池
ExecutorService a = Executors.newFixedThreadPool(2);//2是线程池中的线程数量
//调用submit:传递实现类线程任务,执行 run 方法
a.submit(new runnable00());
a.submit(new runnable00());
//调用shutdown:关闭线程池,一般不建议执行
a.shutdown();
//这时就会抛出异常,因为线程池没有了
a.submit(new runnable00());
}