多线程-备忘录

跳转到总目录

多线程

分类: 用户线程和守护线程(GC垃圾回收就是),关系如同兔死狗烹,鸟尽弓藏.

1. 创建方式

  • 继承Thread

让一个类继承(extands)Thread类,并重写run()方法,然后new 该类即可,start()启动线程.

  • 实现Runnalle接口

让一个类实现(implements)Runnable接口,并重写run()方法,然后new Thread(new 该类)即可,start()启动线程.

  • 实现Callable接口

让一个类实现(implements)Callable接口,并重写run()方法,然后new Thread(new FutrueTask(new 该类))即可,start()启动线程.如有返回值,FutrueTask.get()获取.

  • 线程池(ThreadPool)创建
       ExecutorService executorService = Executors.newFixedThreadPool(10);//可重用固定线程池
       ThreadPoolExecutor service = (ThreadPoolExecutor) executorService;
       service.execute(适用于Runnable);//需自己提供 new Runnable实现类
       service.submit(适用于Callable);//无需提供参数.
       service.shutdown();

2. 生命周期

在这里插入图片描述

3. 常用方法

start(): 启动当前线程,并调用该线程的run();
run(): 如果直接使用,会运行重写过的run()中的操作,不启动线程
currentThread(): 静态方法,返回执行当前代码的线程.
getName(): 获取线程名.
setName(): 设置线程名.
yeild(): 释放当前CPU的执行权,可以再抢到.
join(): 在线程a总调用线程b的join(),此时线程a进入阻塞状态,直到线程b完全执行完后,线程a才会结束阻塞状态.
stop(): 已过期,强制结束当前线程.
isAlive(): 判断线程是否存活.
sleep(long millitime): 让当前线程睡眠指定的millitime毫秒,在指定的millitime中,当前线程是阻塞状态,但不释放同步监视器(锁).
getPriority(): 获取当前线程的优先级.
setPriority(int newPriority): 设置优先级(1-10),提供常量Thread.MAX_PRIORITY为10,Thread.MIN_PRIORITY为1,默认Thread.NORM_PRIORITY为5.
优先级补充说明:高优先级会抢占低优先级线程CPU的执行权,但只是从概率上高优先级会有高概率执行,并非意味着高优先级执行完才会执行低优先级.

4. 线程不安全解决方式

方式一: 同步代码块

	synchronized(同步监视器(俗称锁,多线程时必须同一把锁)){
		//...需要被同步的代码(即多线程操作的共享变量).
	}

方式二: 同步方法(与同步代码块类似,只不过需要操作的代码为一个方法)

  1. 同步方法仍涉及到同步监视器,只是不用显示声明.
    2. 非静态的同步方法,同步监视器为this.
    3. 静态的同步方法,同步监视器为当前类本身.

方式三: Lock(一般实例化该接口下的ReentrantLock(重入锁))

	private ReentrantLock lock = new ReentrantLock();
	//默认参数为false(即不公平锁,自己抢执行权),改为true后变为FIFO(先进先出)模式.
	try{
		lock.lock();//调用锁定方法(加锁),要确保lock是唯一的,必要时加上static.
		//代码逻辑...
	}finally{
		lock.unlock();//解锁.
	}

5. synchronized和Lock异同

同: 二者都可以解决线程安全问题.
异: synchronized机制在执行完同步代码后自动释放同步监视器,
Lock需要手动启动同步(lock()),同时结束时也需手动的实现(unlock()).

6. 线程通信

以下3个方法必须使用在同步代码块或同步方法中(即synchronized中):

  • wait(): 一旦执行当前线程进入阻塞状态,并释放同步监视器(注wait(long timeout)是可以设时间的).
  • notify(): 唤醒一个被wait()的线程,如果有多个唤醒优先级高的.
  • notifyAll(): 唤醒所有wait()线程.
public class CommunicationTest {
    public static void main(String[] args) {
        Number number = new Number();
        Thread t1 = new Thread(number);
        Thread t2 = new Thread(number);
        t1.start();
        t2.start();

    }
}

class Number implements Runnable{
    private int num =1;
    @Override
    public void run() {
        while (true){
            synchronized (CommunicationTest.class) {
                //锁定哪个对象就用哪个对象来执行notify(), notifyAll(),wait(), wait(long), wait(long, int)操作
                CommunicationTest.class.notify();//唤醒wait的线程
                if (num<=100){
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName()+": "+num++);
                    try {
                        CommunicationTest.class.wait();//是线程进入阻塞状态,并释放锁
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }else {
                    break;
                }
            }
        }
    }
}

必须用synchronized中的同步监视器来调用wait(),notify(),notifyAll(),否则会报IllegalMonitorStateException(非法监控状态)异常.
注: 以上三个方法都是Object中的,非Thread中的.

7. 经典例题:生产者/消费者问题

在这里插入图片描述
具体代码如下:

public class ProductTest {
    public static void main(String[] args) {
        Clerk clerk = new Clerk();
        Producer p1 = new Producer(clerk);
        Customer c1 = new Customer(clerk);
        Customer c2 = new Customer(clerk);
        p1.setName("生产者1");
        c1.setName("消费者1");
        c2.setName("消费者2");
        p1.start();
        c1.start();
        c2.start();
    }
}

class Clerk{
    private int productCount = 0;

    public synchronized void producerProduct() {
        if (productCount<20){
            System.out.println(Thread.currentThread().getName()+": "+"正在生产第"+ ++productCount+"个产品");
            notify();
        }else{
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public synchronized  void customerCustome() {
        if (productCount>0){
            System.out.println(Thread.currentThread().getName()+": "+"正在消费第"+productCount--+"个产品");
            notify();
        }else {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class Producer extends Thread{ //生产者
    private Clerk clerk;

    public Producer(Clerk clerk) {
        this.clerk = clerk;
    }

    @Override
    public void run() {
        while (true){
            try {
                sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            clerk.producerProduct();
        }
    }
}

class Customer extends Thread{//消费者
    private Clerk clerk;

    public Customer(Clerk clerk) {
        this.clerk = clerk;
    }

    @Override
    public void run() {
        while (true){
            try {
                sleep(20);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            clerk.customerCustome();
        }
    }
}

8. sleep()与wait()异同

同: 一旦执行,都可以使得当前线程进入阻塞状态.
异:

  • 声明位置不同: Thread类中声明sleep(),Object类中声明wait().
  • 调用的要求不同: sleep()可以在任何场景下调用,wait()必须在同步代码块或同步方法中(即synchronized中).
  • 释放锁情况: 都使用在synchronized中,sleep()不会释放同步监视器(锁),wait()会释放.
  • Thread.sleep()不需要唤醒(休眠结束后退出阻塞),不会释放锁(类似暂停).
  • Object.wait()不指定时间需要被别人唤醒,会释放锁,而且会加入等待队列(类似等待).

9. 演示线程的死锁

死锁的理解:
不同的线程分别占用对方需要的同步资源不放弃,都在等待对方放弃自己需要的同步资源,就形成了线程的死锁.
说明:
出现死锁后,不会出现异常,不会出现提示,只是所有的线程都处于阻塞状态,无法继续.
我们使用同步时,要避免出现死锁.

public class DeadLock {
    public static void main(String[] args) {
        StringBuffer s1 = new StringBuffer();
        StringBuffer s2 = new StringBuffer();

        new Thread(){
            @Override
            public void run() {
                synchronized (s1){
                    s1.append("Conster");
                    s2.append("1");
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    synchronized (s2){
                        s1.append("b");
                        s2.append("2");
                        System.out.println(s1);
                        System.out.println(s2);
                    }
                }
            }
        }.start();

        new Thread(){
            @Override
            public void run() {
                synchronized (s2){
                    s1.append("c");
                    s2.append("3");
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    synchronized (s1){
                        s1.append("d");
                        s2.append("4");
                        System.out.println(s1);
                        System.out.println(s2);
                    }
                }
            }
        }.start();
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值