Java多线程
线程通信
-  
这是一个线程同步,生产者和消费者共享同一个资源,并且生产者和消费者之间相互依赖,互为条件。
 -  
java提供了几个方法解决线程之间的通讯问题
方法名 作用 wait() 表示线程一直等待,直到其他线程通知,与sleep不同,会释放锁 wait(long timeout) 指定等待的毫秒数 notify() 唤醒一个处于等待状态的线程 notifyAll() 唤醒同一个对象上所有调用wait()方法的线程,优先级别高的线程优先级调度 注意:均是Object类的方法,都是只能在同步方法或者同步代码块中使用,否则会抛出异常IIIegalMonitorStateExeception
 -  
测试:生产者,消费者模型–>利用缓冲区解决:管程法
 
package top.dty.process;
//测试:生产者,消费者模型-->利用缓冲区解决:管程法
//生产者,消费者,产品,缓冲区
public class TestPC {
    public static void main(String[] args) {
        SynContainer container = new SynContainer();
        new Producer(container).start();
        new Consumer(container).start();
    }
}
//生产者
class Producer extends Thread{
    SynContainer container;
    public Producer(SynContainer container){
        this.container = container;
    }
    @Override
    public void run() {
        for (int i =0; i < 100; i++) {
//            System.out.println("生产了"+i+"个产品");
            container.push(new Product(i));
            System.out.println("生产了"+i+"个产品");
        }
    }
}
//消费者
class Consumer extends Thread{
    SynContainer container;
    public Consumer(SynContainer container){
        this.container = container;
    }
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("消费-->"+container.pop().id+"个产品");
        }
    }
}
//产品
class Product{
    int id;//产品编号
    public Product(int id) {
        this.id = id;
    }
}
//缓冲区
class SynContainer{
    //需要一个容器的大小
    Product[] products = new Product[10];
    //容器计数器
    int count = 0;
    //生产者放入产品
    public synchronized void push(Product product){
        //如果容器慢的话,就需要等待消费者消费
        if(count==products.length){
            //通知消费者消费,生产者等待
        }
        //如果没有满的话,我们就要丢人商品
        products[count]=product;
        count++;
        //可以通知消费者消费了
    }
    //消费者消费产品
    public synchronized  Product pop(){
        //判断能否消费
        if(count<=0){
            //等待生产者消费
        }
        //如果可以消费的
        count--;
        Product product =products[count];
        //吃完了,通知生产者消费
        return product;
    }
}
 
- //测试生产者消费者问题;信号灯法,标志位解决
 
package top.dty.process;
//测试生产者消费者问题;信号灯法,标志位解决
public class TestPC3 {
    public static void main(String[] args) {
        TV tv = new TV();
        new Player(tv).start();
        new Watcher(tv).start();
    }
}
//生产者-->演员
class Player extends Thread{
    TV tv;
    public Player(TV tv){
        this.tv = tv;
    }
    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            if(i%2==0){
                this.tv.play("快乐大本营");
            }else {
                this.tv.play("广告");
            }
        }
    }
}
//消费者-->观众
class Watcher extends Thread{
    TV tv;
    public Watcher(TV tv){
        this.tv = tv;
    }
    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            tv.watch();
        }
    }
}
//产品-->节目
class TV{
    //演员表演,观众等待
    //观众观看,演员等待
    String voice;//表演的节目
    boolean flag = true;
    //表演
    public synchronized void play(String voice){
        if(!flag){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("演员表演了:"+voice);
        //通知群众观看
        this.notifyAll();//通知唤醒
        this.voice = voice;
        this.flag = !this.flag;
    }
    //观看
    public synchronized void watch(){
        if(flag){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("观看了:"+voice);
        //同时演员表演
        this.notifyAll();
        this.flag = !this.flag;
    }
}
 
使用线程池
- 背景:经常创建和销毁,使用量特别大的资源,比如并发情况下的线程,对性能影响很大
 - 思路:提前创建好多个线程,放入线程池中,使用时直接获取,使用完放回池中。可以避免频繁创建销毁,实现重复利用。类似生活中的公共交通工具。
 - 好处: 
  
- 提高响应速度(减少了创建线程的时间)
 - 降低资源消耗(重复利用线程池中线程,不需要每次都创建)
 - 便于线程管理 
    
- corePoolSize:核心池的大小
 - maximumPoolSize:最大线程数
 - keepAliveTime:线程没有任务时最多保持多长时间会终止
 
 
 - JDK5.0起提供了线程池相关API:ExecutorSerice和Exexutors
 - ExecutorSerice:真正的线程池接口。常见子类ThreadPoolExecutor 
  
- void execute(Runnable command):执行任务/命令,没有发回值,一般用来执行Runnable
 - Futuresubmit(Callabletask):执行任务,有返回值,一般又来执行Callabe
 - void shutdown():关闭连接池
 
 - Exexutors:工具类,线程池的工厂类,用于创建并返回不同类型的线程池
 
package top.dty.process;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TestPool {
    public static void main(String[] args) {
        //1.创建服务,创建线程池
        //newFixedThreadPool 线程:线程池大小
        ExecutorService service = Executors.newFixedThreadPool(10);
        //执行
        service.execute(new MyTread());
        service.execute(new MyTread());
        service.execute(new MyTread());
        service.execute(new MyTread());
        //2.关闭链接
        service.shutdown();
    }
}
class MyTread implements Runnable{
    @Override
    public void run() {
            System.out.println(Thread.currentThread().getName());
    }
}










