java多线程总结

Java多线程总结

线程的概念

在开始学习编程时,我们写的程序都是顺序执行。
例如这个场景:我们正在烧水等水开,此时有人敲门,我们需要等水烧开再去开门,这是单线程顺序执行(容易造成阻塞)。那么多线程呢?在等水烧开的时候,有人敲门那么我们就是开门,之后继续去烧水。也就是事情没有被阻塞住。

我们在写顺序程序的时候其实是有一个线程的,并且只有一个线程。多个线程是为了合理利用cup,加快事情的处理。

jvm(虚拟机)是运行在os(操作系统)之上的软件,我们的编写的程序是运行在jvm上的。 jvm是os的一个进程。进程之间的上下文切换相比线程开销更大。

一个进程可以包含多个线程,可以这样理解线程是轻量级的进程。

进程:每个进程都有独立的代码和数据空间(进程上下文),进程间的切换会有比较大的开销,一个进程包含1-n个线程。(进程是资源分配的最小单位)

线程:同一类线程共享代码和数据空间,每个线程有独立的运行栈和程序计数器(pc program count),线程切换开销小。(线程是cup调度的最小单位)。

从以上的定义中我们可以得出以下信息:

进程中的变量是不相互访问的,多线程可以共享变量(这个是在线程开发中经常要解决的问题)

线程的状态

线程有五个状态:初始化,就绪,运行,阻塞,终止。

线程状态切换:

线程状态切换

初始状态:线程被创建,出生。

可运行:线程处于就绪状态,等待cup调度。

运行中:cup调度运行线程。

结束: 线程执行完毕,死亡。

阻塞状态:线程等待用户输入。。。。

Java的Thread和Runnable

java中实现线程有两种方式:

  1. 继承Thread类。
  2. 实现Runnable接口。

继承Thread

package xuelongjiang.baseGrama.thread;

/**
 *
 * 继承Thread方式
 * @Author xuelongjiang
 */
public class ThreadExample extends  Thread {

    @Override
    public void run() {
        for(int i = 0; i<5;i++){
            System.out.println(Thread.currentThread() +":"+ i);
        }
    }


    public static void main(String[] args) {

        ThreadExample example1 = new ThreadExample();
        ThreadExample example2 = new ThreadExample();

        example1.start();
        example2.start();

    }
}

输出:
Thread[Thread-0,5,main]:0
Thread[Thread-0,5,main]:1
Thread[Thread-0,5,main]:2
Thread[Thread-0,5,main]:3
Thread[Thread-0,5,main]:4
Thread[Thread-1,5,main]:0
Thread[Thread-1,5,main]:1
Thread[Thread-1,5,main]:2
Thread[Thread-1,5,main]:3
Thread[Thread-1,5,main]:4

实现Runnable

package xuelongjiang.baseGrama.thread;

/**
 *
 * 简单线程
 * @Author xuelongjiang
 */
public class RunnableExampleOne {


    public static void main(String[] args) {

        Example example1 = new Example();
        example1.setName("线程1");

        Example example2 = new Example();
        example2.setName("线程2");


        Thread t1 =  new Thread(example1);
         Thread t2 = new  Thread(example2);

         t1.setPriority(Thread.MAX_PRIORITY);

         t2.setPriority(Thread.MIN_PRIORITY);

         //one  不会按照优先级
        t2.start();
        t1.start();

        //two 线程会按照优先级
        //t1.start();
        //t2.start();
    }

}




class Example implements  Runnable{

    String name = "线程";
    public void setName(String name ){
        this.name = name;
    }

    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see Thread#run()
     */
    @Override
    public void run() {
        for(int i = 0; i<5;i++){
            System.out.println(name +":"+ i);
        }
    }
}

输出:
线程2:0
线程2:1
线程2:2
线程2:3
线程2:4
线程1:0
线程1:1
线程1:2
线程1:3
线程1:4

两种实现线程的对比

  • 由于Java的继承是单继承,使用Runnable可以是程序保持更好的扩展性
  • 适合多个相同的程序代码的线程去处理同一个资源
  • 线程池只能放入实现 Runable类线程,不能直接放入继承Thread的类

我们观察Runnable和Thread线程的最终运行都是Thread.start(),所以最终线程的运行时需要Thread类的,并且Thread实现了Runnable接口。

线程中的方法

wait() notify() notifyAll()

wait(),notify(),notifyAll()是object类的方法。

  • wait() :会使当前线程进入等待队列,并且会释放当前线程所持有的锁。
  • notify(),notifyAll():notifyall和notify都是释放执行了wait方法的线程使wait的线程重新进入就绪状态。nofity()唤醒一个,nofityAll()唤醒所有执行wait()方法的线程。

线程——>wait() ————> 等待。
线程 ——-> notify(),notifyAll(). ————>等待的线程进入就绪状态

理解wait(),notify(),notifyAll()的最好示例是 消费-生产模型。
生产和消费者共同争夺同一个资源。如果资源目前不能使用则当前线程执行wait进入等待队列,如果可以使用当使用完毕后则释放在等待区的线程。

talk is cheap ,show you code!!

工厂接口StorageInterface
package xuelongjiang.baseGrama.thread.waitNotifyThread;

/**
 * 工厂接口,存储生产消费的资料
 * @Author xuelongjiang
 */
public interface StorageInterface {

    void consume(int num);//消费者

    void produce(int num);//生产者

}

工厂实现类Storage
package xuelongjiang.baseGrama.thread.waitNotifyThread;

import java.util.LinkedList;

/**
 * 生产和消费的实现类
 *
 * 本质是生产者和消费者对 LinkedList进行操作
 *  因为LinkedList不是线程安全的,所以需要我们编写代码保证线程安全
 *
 * @Author xuelongjiang
 */
public class Storage implements  StorageInterface {


    private LinkedList list = new LinkedList();//容器,线程争抢资源


    private final  int MAX_SIZE = 100;// 最大容量


    /**
     * 消费
     * @param num
     */
    @Override
    public void consume(int num) {

        synchronized (list){

            while (list.size()<num){

                System.out.println("【想要消费的产品数量:】"+num+" ; 库存量:"+list.size()+",暂时不能执行消费任务");

                try {
                    list.wait();
                }catch (InterruptedException e ){
                    e.printStackTrace();

                }

            }


            for(int i = 0;i<num; i++){
                list.remove();
            }

            System.out.println("【已经消费产品数:】"+num+" ; 仓库现在剩余:"+ list.size());
            list.notifyAll();
        }

    }


    /**
     * 生产
     * @param num
     */
    @Override
    public void produce(int num) {

        synchronized (list){

            while (list.size()+num>MAX_SIZE){
                System.out.println("【想要生产产品】:"+num  +"; 【库存已经存量】:"+list.size());


                try {
                    list.wait();//会放弃锁

                }catch (InterruptedException e){
                    e.printStackTrace();
                }

            }

            for(int i =0;i<num;i++){

                list.add(new Object());
            }

            System.out.println("【生产产品】:"+num+"; 【目前库存量】:"+list.size());

            list.notifyAll();
        }


    }
}

消费者Consumer
package xuelongjiang.baseGrama.thread.waitNotifyThread;

/**
 * 消费者
 * @Author xuelongjiang
 */
public class Consumer  extends  Thread{


    private int num;

    private StorageInterface storage;


    public  Consumer(StorageInterface storage){
        this.storage = storage;
    }


    public void setNum(int num){
        this.num = num;
    }


    @Override
    public void run() {
        consume(num);

    }


    public void  consume(int num){

        storage.consume(num);//调用工厂的消费

    }

}

生产者Producer
package xuelongjiang.baseGrama.thread.waitNotifyThread;

/**
 *
 * 生产者
 * @Author xuelongjiang
 */
public class Producer extends  Thread {


    private int num ;//每次生产的数量


    private  StorageInterface storage;

    public Producer(StorageInterface storage){
        this.storage = storage;
    }

    public  void setNum(int num){
        this.num = num;
    }

    @Override
    public void run() {
        produce(num);
    }


    public void produce(int num){
        storage.produce(num);
    }
}

生产消费者测试
package xuelongjiang.baseGrama.thread.waitNotifyThread;

/**
 * 生产--消费者 测试
 *
 * @Author xuelongjiang
 */
public class WaitNofityThreadExample {


    public static void main(String[] args) {

        StorageInterface storage = new Storage();//消费生产同一个工厂

        //生产者
        Producer p1   = new Producer(storage);
        Producer p2   = new Producer(storage);
        Producer p3   = new Producer(storage);
        Producer p4   = new Producer(storage);
        Producer p5   = new Producer(storage);

        //消费者
        Consumer c1 = new Consumer(storage);
        Consumer c2 = new Consumer(storage);
        Consumer c3 = new Consumer(storage);
        Consumer c4 = new Consumer(storage);
        Consumer c5 = new Consumer(storage);

        //设置生产数量
        p1.setNum(20);
        p2.setNum(10);
        p3.setNum(30);
        p4.setNum(50);
        p5.setNum(10);

        //设置消费数量
        c1.setNum(5);
        c2.setNum(10);
        c3.setNum(15);
        c4.setNum(20);
        c5.setNum(25);

        c1.start();
        c2.start();
        c3.start();
        c4.start();
        c5.start();

        p1.start();
        p2.start();
        p3.start();
        p4.start();
        p5.start();
    }
}

输出:
想要消费的产品数量:】5 ; 库存量:0,暂时不能执行消费任务

【想要消费的产品数量:】10 ; 库存量:0,暂时不能执行消费任务

【想要消费的产品数量:】15 ; 库存量:0,暂时不能执行消费任务

【想要消费的产品数量:】20 ; 库存量:0,暂时不能执行消费任务

【想要消费的产品数量:】25 ; 库存量:0,暂时不能执行消费任务

【生产产品】:20; 【目前库存量】:20

【想要消费的产品数量:】25 ; 库存量:20,暂时不能执行消费任务

【已经消费产品数:】20 ; 仓库现在剩余:0

【想要消费的产品数量:】15 ; 库存量:0,暂时不能执行消费任务

【想要消费的产品数量:】10 ; 库存量:0,暂时不能执行消费任务

【想要消费的产品数量:】5 ; 库存量:0,暂时不能执行消费任务

【想要消费的产品数量:】25 ; 库存量:0,暂时不能执行消费任务

【生产产品】:10; 【目前库存量】:10

【想要消费的产品数量:】25 ; 库存量:10,暂时不能执行消费任务

【已经消费产品数:】5 ; 仓库现在剩余:5

【想要消费的产品数量:】10 ; 库存量:5,暂时不能执行消费任务

【生产产品】:50; 【目前库存量】:55

【已经消费产品数:】15 ; 仓库现在剩余:40

【已经消费产品数:】10 ; 仓库现在剩余:30

【已经消费产品数:】25 ; 仓库现在剩余:5

【生产产品】:30; 【目前库存量】:35

【生产产品】:10; 【目前库存量】:45

sleep()和yield()

Yield()和sleep()区别是:
sleep会使线程进入休眠(阻塞状态),休眠时间由程序设定。yield()使当前线程进入就绪状态和其他线程一起等待os调度。也就是说yield的线程可能会立马有重新执行,或者和他同等优先级的线程执行。
yield()从未导致线程转到等待/睡眠/阻塞状态。在大多数情况下说,yeild()将导致线程从运行状态转到可运行状态,很有可能没有效果。
Sleep()不会释放锁,而wait()会释放锁。

join()

线程加入:join方法,等待其他线程终止,在当前线程中调用另一个线程的join方法,则当前线程转入阻塞状态,直到另一个线程结束,当前线程再由阻塞转为就绪状态。

package xuelongjiang.baseGrama.thread;

/**
 * join()方法示例
 *
 * join会阻塞当前线程
 * @Author xuelongjiang
 */
public class ThreadJoinExample {


    public static void main(String[] args) throws Exception {

        RunnableExample example1 = new RunnableExample();
        RunnableExample example2 = new RunnableExample();

        example1.setName("线程1");
        example2.setName("线程2");

        Thread thread1 = new Thread(example1);
        Thread thread2 = new Thread(example2);

        thread1.start();
        thread1.join(); //join执行后,thread2必须等待线程1执行完毕才开始执行
        thread2.start();

    }
    
}

输出:
线程1:0
线程1:1
线程1:2
线程1:3
线程1:4
线程2:0
线程2:1
线程2:2
线程2:3
线程2:4

需要注意的是join()方法需要在执行join方法线程的start()之后,在其他线程start()之前。

守护线程和用户线程setDaemon() isDaemon()

守护线程:是指在程序运行的时候在后台提供一种通用服务的线程,比如垃圾回收线程就是一个守护线程。并且守护线程会随着用户线程的结束而结束。
用户线程:我们创建的线程。

isDaemon():判断线程是否是守护线程
setDaemon(boolean on):设置线程是否为守护线程。true:设置线程为守护线程,false:设置线程不为守护线程

synchronized

sychronized用来对一个方法或代码块进行加锁。特别注意的是Java是类锁,也就是如果对象的好几个方法都有加锁,那么如果A线程获取到了一个方法的锁,那么B线程调用其他加synchronized的方法,需要A先释放锁。

线程池

为什么需要线程池

线程的生命周期是:创建线程(耗费时间t1),运行线程(耗费时间t2),结束线程(耗费时间t3)。

如果t1+t3>t2,那么会浪费很多cup资源。我们可以通过使用线程池来节省t1+t3的时间。

线程池:承载线程的容器
线程:承载任务的容器
任务:具体的功能代码

线程池的使用

我们来来看代码理解三种线程池:

任务
class LiftOff  implements Runnable { //任务需要继承Runnable接口
	
	protected int countDown = 10;
	private static int taskCount = 0;
	private final int id = taskCount++;
	
	public LiftOff() {}
	public LiftOff(int countDown){
		this.countDown = countDown;
	}
	
	public String  status() {
		return "#"+id+"("+
				(countDown>0?countDown:"LiftOff") +"),";
	}
	
	public void run() { //重写父类的run,在线程执行的时候,执行这个任务
		while(countDown-- > 0){
			System.err.print(status());
			/**
			 * 线程调度器,声明我已经执行完生命周期最重要的部分,
			 * 此刻整正是切换给其他任务执行一段时间的大好时机
			 */
			Thread.yield(); //选择行使用
		}
	}
}

singleThread
package xuelongjiang.baseGrama.threadPool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * SingleThread线程 里面的每个任务都必须等待上一个任务执行完毕才能执行
 * SingleThread里面的任务,不会出现死锁
 * @author xuelongjiang
 *
 */
public class SingleThread {

	public static void main(String []args){

		ExecutorService exec = Executors.newSingleThreadExecutor();
		for(int i = 0;i<10;i++ ){
			exec.execute(new LiftOff());
		}
		exec.shutdown();
		System.err.println("Waiting Thread");

	}


}

fixedThread
package xuelongjiang.baseGrama.threadPool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 使用有限的线程
 * @author xuelongjiang
 *
 */
public class FixedThreadPool {

	public static void main(String [] args){
		
		ExecutorService exce = Executors.newFixedThreadPool(10);
		for(int i = 0;i<10;i++){
			exce.execute(new LiftOff());
		}
		exce.shutdown();
		System.err.println("Wating Thread");
	}
	
}
cacheThread
package xuelongjiang.baseGrama.threadPool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Executor允许你管理异步任务的执行
 * 而无需显式的管理线程的生命周期
 * Executor 线程执行器
 * 
 * @author xuelongjiang
 * 
 *
 */
public class CacheThreadPool {
	
	public  static void main(String [] args){
			
		ExecutorService exec = Executors.newCachedThreadPool();
		for(int i =0;i<10;i++){
			exec.execute(new LiftOff());
		}
		exec.shutdown();
		System.err.println("Waiting Thread ");
	}
}

自定义线程池

自定义线程池关注核心七个参数:核心线程池大小、最大线程池大小、空闲线程存活的时间、线程存活时间单位、阻塞排队队列大小,线程工厂、拒绝策略。

当线程池创建后工作流程是:

当核心线程池大小未满创建继续核心线程 ------> 加入阻塞队列,直到队列满了 -----> 创建线程直到线程数等于最大线程数---> 再有线程进来,根据拒绝策略,丢弃任务抛异常、丢弃任务不抛异常

public class Test {
  
  public static void main(int[] args) {
		int corePoolSize = 10;
		int maxPoolSize = 20;
		int timeOut = 10;
		int queueSize = 10;
		
		ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, maxPoolSize, timeout, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(queueSize));
	Task task = new Task();
	executor.submit(task);
 }


 public class Task implements Runnable{
  public void run() {
  // 执行线程任务
 }
}

}

问题: 当核心线程池未满,线程池提交了一个任务,为什么不复用已有的线程而是创建新的线程呢?
  1. 预热, 当核心线程未满,认为线程池初始化还未完成,继续创建线程直到满足核心线程数
  2. 复用之前的线程会存在额外的开销(锁开销)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值