【java线程】线程、多线程学习

线程、多线程

一个线程指的是进程中一个单一顺序的控制流,一个进程中可以并发多个线程,每条线程并行执行不同的任务。

进程:
	一个进程包括由操作系统分配的内存空间,包含一个或多个线程。对于计算机而言就是一个独立的程序。
线程是进程的一部分,使用的是程序内部资源,每一个线程都要向进程申请资源,并且当前资源很多都是共享资源。
1、线程生命周期
新建状态--(执行start()方法)---》就绪状态----(获取CPU资源,执行run方法)-----》运行状态---(run方法执行完成)---》死亡状态              当程序阻塞,会出现阻塞状态



新建状态:

	使用new关键字和Thread类或者其子类建立一个线程对象后,该线程对象就处于新建状态,直到start();

就绪状态:

	当线程对象调用了start()方法,该线程进入就绪状态。等待JVM里线程调度器的调度。

运行状态:

	如果就绪状态的线程获取CPU资源,就可以执行run()方法,进入运行状态。

阻塞状态:

	如果一个线程执行了wait(等待),sleep(睡眠),suspend(挂起)等方法,失去所占用资源之后,该线程就从运行状态进入阻塞状态,当睡眠时间到达或获得设备资源后会重新进入就绪状态:

		等待阻塞:运行状态的线程执行wait()方法,使线程进入到阻塞状态

		同步阻塞:线程在获取synchronized同步锁失败

		其他阻塞:通过调用线程的sleep()或join()发出来I/O请求时,线程就会进入到阻塞状态。当sleep()状态超时,join()等待线程终止或超时,或者I/O处理完毕,线程重新进入就绪状态。

死亡状态:

	一个运行状态的线程完成任务或者其他终止条件发生时,该线程就切换到终止状态。
2、线程的创建
2.1 通过实现Runnable接口
创建一个线程,最简单的方法是创建一个实现Runnable接口的类。
package com.example.demo.threadTest;

/**
 * @Author zhangxin
 * @Date 2021/7/13 10:56
 * @Version 1.0
 */
public class RunnableTest  implements Runnable{

    private Thread thread;
    private String threadName;

    public RunnableTest(String threadName) {
        this.threadName = threadName;
        System.out.println("Greating " + threadName);
    }

    @Override
    public void run() {
        System.out.println("Running " + threadName);
        for (int i = 0; i < 4; i++) {
            System.out.println("Thread: " + threadName + ", " + i);
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
                System.out.println("Thread " + threadName + " interrupted");
            }
        }
        System.out.println("Thread " + threadName + "exiting");
    }

    public void start() {
        System.out.println("Starting " + threadName);
        if (thread == null) {
            thread = new Thread(this, threadName);
            thread.start();
        }
    }
}


package com.example.demo.threadTest;

/**
 * @Author zhangxin
 * @Date 2021/7/13 10:25
 * @Version 1.0
 */
public class ThreadTest1 {
    public static void main(String[] args) {
        RunnableTest R1 = new RunnableTest("线程1");
        R1.start();

        RunnableTest R2 = new RunnableTest("线程2");
        R2.start();
    }
}

2.2 通过继承Thread来创建线程
创建一个线程的第二种方法是创建一个新的类,该类继承Thread类,然后创建一个该类的实例。
继承类必须重写run()方法,该方法是新线程的入口点,它也必须调用start()方法才能执行。
package com.example.demo.threadTest;

/**
 * @Author zhangxin
 * @Date 2021/7/13 11:17
 * @Version 1.0
 */
public class ThreadExtendsTest extends Thread{
    private Thread thread;
    private String threadName;

    public ThreadExtendsTest(String threadName) {
        this.threadName = threadName;
        System.out.println("Greating " + threadName);
    }

    @Override
    public void run() {
        System.out.println("Running " + threadName);
        for (int i = 0; i < 4; i++) {
            System.out.println("Thread: " + threadName + "," + i);
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
                System.out.println("Thread " + threadName + " interrupted");
            }
        }
        System.out.println("Thread " + threadName + "exiting");
    }

    @Override
    public synchronized void start() {
        System.out.println("Starting " + threadName);
        if (thread ==  null) {
            thread = new Thread(this, threadName);
            thread.start();
        }
    }
}


 ThreadExtendsTest T1 = new ThreadExtendsTest("线程1");
        T1.start();

        ThreadExtendsTest T2 = new ThreadExtendsTest("线程2");
        T2.start();
2.3 通过Callable和Future创建线程
1、创建Callable接口的实现类,并实现call()方法,该call()方法将作为线程执行体,并且有返回值。
2、创建Callable实现类的实例,使用FutureTask类来包装Callable对象,该FutureTask对象封装了该Callable对象的call()方法的返回值
3、使用FutureTask对象作为Thread对象的target创建并启动新线程
4、调用FutureTask对象的get()方法来获取子线程执行结束后的返回值。
package com.example.demo.threadTest;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * @Author zhangxin
 * @Date 2021/7/13 13:42
 * @Version 1.0
 */
public class CallableThreadTest implements Callable<Integer> {
    
    // 实现call方法,作为线程执行体,并且有返回值
    @Override
    public Integer call() throws Exception {
        int i = 0;
        for (; i < 50; i++) {
            System.out.println(Thread.currentThread().getName() + " " + i);
        }

        return i;
    }

    public static void main(String[] args) {
        // 创建Callable实现类的实例
        CallableThreadTest callableThreadTest = new CallableThreadTest();
        // 使用FutureTask类来包装Callable对象
        FutureTask<Integer> futureTask = new FutureTask<>(callableThreadTest);
        for (int i = 0; i < 50; i++) {
            System.out.println(Thread.currentThread().getName() + "的循环变量i的值: "+i);
            if(i == 20) {
                // 使用FutureTask对象作为Thread对象的target创建并启动新线程
                new Thread(futureTask, " 有返回值的线程").start();
            }
        }
        try {
            // 调用FutureTask对象的get方法来获得子线程执行结束后的返回值
            System.out.println("子线程的返回值:" + futureTask.get());
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
}

3、线程安全问题
线程同步:在同步代码块中,只能存在一个线程。
线程安全问题:是指多个线程对同一个共享数据进行操作时,线程没来得及更新共享数据,从而导致另外线程没得到最新的数据,从而产生线程安全问题。
例子:
	有一个厕所,有人进去了,但是没有上锁,预于是别人不知道你进去了,别人也进去了对厕所的使用造成错误。
3.1 同步代码块
使用同步监视器(锁)
Synchronized(同步监视器) {
   // 需要被同步的代码
}
1、操作共享数据的代码,即为同步代码块
2、共享数据,多个线程共同操作的数据
3、同步监视器(锁),任何一个对象都可以充当锁,当锁住以后只能一个线程能进去
3.2 同步方法
使用同步方法,对方法进行Synchronized关键字修饰
将同步代码块提取出来成为一个方法,用synchronized关键字修饰
对于runnable接口实现多线程,只需要将同步方法用synchronized修饰
对于继承自Thread方式,需要将同步方法用static和synchd修饰,因为对象不唯一(锁不唯一)
3.3 JDK5新增的lock锁方法
package com.example.demo.threadTest;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author zhangxin
 * @Date 2021/7/13 14:31
 * @Version 1.0
 */
public class WindowTest implements Runnable{
    // 定义100张票
    private int ticket = 100;
    private ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true) {
            // 调用锁定方法lock
            lock.lock();
            if (ticket > 0) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "售出第 " + ticket + " 票");
                ticket--;
            } else {
                break;
            }
        }
    }
}


package com.example.demo.threadTest;

/**
 * @Author zhangxin
 * @Date 2021/7/13 14:30
 * @Version 1.0
 */
public class ThreadTest2 {
    public static void main(String[] args) {
        WindowTest windowTest = new WindowTest();
        Thread t1 = new Thread(windowTest);
        Thread t2 = new Thread(windowTest);
        Thread t3 = new Thread(windowTest);

        t1.setName("窗口1");
        t2.setName("窗口1");
        t3.setName("窗口1");

        t1.start();
        t2.start();
        t3.start();
    }
}


4、线程通信
4.1 wait/notify机制
线程间通过共享数据来实现通信,即多个线程主动地读取一个共享数据,通过同步互斥访问机制确保线程的安全性。
等待/通知机制主要由Object类中的wait(),notify()和notifyAll()三个方法来实现。这三个方法都不是Thread类中所声明的方法,而是Object类中声明的方法。原因是每个对象都拥有monitor(锁),所以让当前线程等待某个对象的锁,当然应该通过这个对象来操作,而不是用当前线程来操作,因为当前线程可能会等待多个线程的锁。

wait():
	让当前线程释放对象锁并进入等待状态。
notify():
	唤醒一个正在等待相应对象锁的线程,使其进入就绪队列,以便在当前线程释放锁后竞争锁,进而得到CPU的执行
notifyAll():
	唤醒所有正在等待相应对象锁的线程,使他们进入就绪队列,以便在当前线程释放锁后竞争锁,进而得到CPU的执行。
wait(),notify(),和notifyAll()方法是本地方法,并且为final方法,无法被重写;调用某个对象的wait()方法能让当前线程阻塞,并且当前线程必须拥有此对象的monitor(锁);调用某个对象的notify()方法能唤醒一个正在等待这个对象的monitor的线程,如果有多个线程都在等待这个对象的monitor,则只能唤醒其中一个线程;调用notifyAll()方法能唤醒所有正在等待这个对象的monitor的线程。

每个锁对象都有两个队列,一个是就绪队列,一个是阻塞队列。就绪队列存储了已就绪的线程,阻塞队列存储了呗阻塞的队列。
4.2 生产者、消费者模式
package com.example.demo.threadTest;

/**
 * @Author zhangxin
 * @Date 2021/7/13 15:18
 * @Version 1.0
 */
public class Producer implements Runnable{

    Goods goods;

    public Producer() {
    }

    public Producer(Goods goods) {
        this.goods = goods;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (goods) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                // 商品需要生产
                if (goods.isProduct()) {
                    if (Math.random() > 0.5) {
                        goods.setName("吉利星越");
                        goods.setPrice(10000);
                    } else {
                        goods.setName("吉利帝豪");
                        goods.setPrice(1324);
                    }
                    System.out.println("产品" + goods.getName() + "已经被生产者生产,售价:" + goods.getPrice());

                    goods.setProduct(false);
                    // 唤醒消费者
                    goods.notify();
                    System.out.println("唤醒消费者");
                } else {
                    // 商品不需要生产,生产者休眠
                    System.out.println("生产者休眠");
                    try {
                        goods.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}


package com.example.demo.threadTest;

/**
 * @Author zhangxin
 * @Date 2021/7/13 15:26
 * @Version 1.0
 */
public class Customer implements Runnable{

    Goods goods;

    public Customer() {
    }

    public Customer(Goods goods) {
        this.goods = goods;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (goods) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                // 商品不需要生产,消费者购买
                if (!goods.isProduct()) {
                    System.out.println("消费者购买:" + goods.getName() + " 价格:" + goods.getPrice());
                    goods.setProduct(true);
                    System.out.println("唤醒生产者");
                    goods.notify();
                } else {
                    System.out.println("消费者休眠");
                    try {
                        goods.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}


package com.example.demo.threadTest;

/**
 * @Author zhangxin
 * @Date 2021/7/13 15:16
 * @Version 1.0
 */
public class Goods {
    private String name;
    private int price;
    private boolean product;

    public Goods() {
    }

    public Goods(String name, int price, boolean product) {
        this.name = name;
        this.price = price;
        // 是否需要生产 true 需要生产   false 不需要生产
        this.product = product;
    }

    public String getName() {
        return name;
    }

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

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public boolean isProduct() {
        return product;
    }

    public void setProduct(boolean product) {
        this.product = product;
    }
}


package com.example.demo.threadTest;

/**
 * @Author zhangxin
 * @Date 2021/7/13 15:33
 * @Version 1.0
 */
public class GoodsDemo {
    public static void main(String[] args) {
        Goods goods = new Goods("领克05", 16, true);

        Producer producer = new Producer(goods);
        Customer customer = new Customer(goods);

        System.out.println(producer.goods);
        System.out.println(customer.goods);

        new Thread(producer).start();
        new Thread(customer).start();
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值