多线程java

本文详细介绍了Java中多线程的创建方式(继承Thread、实现Runnable和Callable接口),线程池的使用,以及同步机制(乐观锁与悲观锁)的应用。重点讨论了如何启动线程、任务返回结果和处理线程安全问题。
摘要由CSDN通过智能技术生成

多线程的创建

前两种方法无法返回直接结果,而有的线程执行完毕后需要返回结果

方式一:java是通过java.lang.Thread类的对象来代表线程的
  • 启动线程必须调用strat方法,不是调用run方法
  • 不要把主线程任务放在启动子线程之前
//1.让子类继承Thread线程类
public class MyThread extends Thread{
    //2.必须重写Thread类的run方法
    @Override
    public void run(){
        for (int i = 0; i < 5; i++) {
            System.out.println("MyThread线程输出:"+i);
        }
    }
}
public class ThreadTest1 {
    //main
    public static void main(String[] args) {
        //3.创建MyThread线程类的对象代表一个线程
        Thread t = new MyThread();
        //4.启动线程
        t.start();
    }
}
方式二:实现Runnable接口
  • 优点:任务类只是实现接口,可以继续继承其他类,实现其它接口,扩展性强
//1.实现Runnable接口
public class MyRunnable implements Runnable{
    //2.重写run方法
    @Override
    public void run() {
        //3.线程要执行的任务
        for (int i = 0; i < 5; i++) {
            System.out.println("子线程输出:"+i);
        }
    }
}
public class ThreadTest2 {
    public static void main(String[] args) {
        //4.创建任务对象
        Runnable target = new MyRunnable();
        //5.把任务对象交给一个线程处理
        new Thread(target).start();

        for (int i = 0; i < 5; i++) {
            System.out.println("主线程输出:"+i);
        }
    }
}
线程创建方式二的匿名内部类写法
  1. 可以创建Runable的匿名内部类对象
  2. 再交给Thread线程对象
  3. 在调用线程对象的Strat()启动线程
public class ThreadTest2_2 {
    public static void main(String[] args) {
        //1.直接创建Runnable接口的匿名内部类形式(任务对象)
        Runnable target = new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 5; i++) {
                    System.out.println("子线程1输出:"+i);
                }
            }
        };
        new Thread(target).start();

        //简化形式
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 5; i++) {
                    System.out.println("子线程2输出:"+i);
                }
            }
        }).start();

        //再次简化
        new Thread(() -> {
                for (int i = 0; i < 5; i++) {
                    System.out.println("子线程3输出:"+i);
                }
        }).start();

        for (int i = 0; i < 5; i++) {
            System.out.println("主线程输出:"+i);
        }
    }
}
方式三:实现Callable接口
  • JDK5.0提供了Cabble接口和FutureTask类来实现
  • 可以返回线程执行完毕后的结果

过程

  1. 定义一个类实现Callable接口,重写Call方法,封装要做的事,和要返回的数据结果
  2. 把Callable类型的对象封装成FutureTask(线程任务对象)
  3. 把线程任务对象交给Thread对象
  4. 调用start方法启动线程
  5. 线程执行完毕后,通过FutureTask对象的get方法去获取线程任务执行的结果
public class ThreadTest3 {
    public static void main(String[] args) throws Exception {
        //3.创建一个Callable对象
        Callable<String> callable  = new MyCallable(100);
        //4.把Callable对象封装成一个FutureTask对象
        //未来任务对象
        //1.是一个任务对象,实现了Runnable接口
        //2.可以在线程执行完毕之后,用未来任务对象调用get方法获取线程完毕后的结果
        FutureTask<String> futureTask = new FutureTask(callable);

        new Thread(futureTask).start();

        //6.获取线程执行完毕后的结果
        System.out.println(futureTask.get());
    }
}
//1.让这个类实现Callable接口
public class MyCallable implements Callable {
    private int n;

    public MyCallable(int n) {
        this.n = n;
    }

    //2.重写call方法
    //求1-n的和

    int sum = 0;
    @Override
    public String call() throws Exception {
        for (int i = 1; i <=n; i++) {
            sum=sum+i;
        }
        return "线程求出了1-n的和是:"+sum;
    }
}

线程的方法

public class MyThread extends Thread{
    public MyThread(String name) {
        super(name);

    }

    @Override
    public void run(){
        Thread m = Thread.currentThread();

        for (int i = 0; i < 3; i++) {
            System.out.println(m.getName()+"子线程输出:"+i);
        }
    }
}
public class ThreadTest1 {
    public static void main(String[] args) {
        Thread t1 = new MyThread("一号线程");
        //设置名字
//        t1.setName("一号线程");
        t1.start();
        System.out.println(t1.getName());

        //构造器设置名字
        Thread t2 = new MyThread("二号线程");
        t2.start();
        System.out.println(t2.getName());

        //主线程对象的名字
        Thread m = Thread.currentThread();//那个线程执型它,他就会得到哪个对象
        System.out.println(m.getName());

        for (int i = 0; i < 4; i++) {
            System.out.println("main线程输出:"+i);
        }
    }
}
//sleep  join   的作用
public class ThreadTest2 {
    public static void main(String[] args) throws Exception {
        for (int i = 0; i < 5; i++) {
            //到3的时候休眠五秒
            if(i==3){
                Thread.sleep(5000);
            }
            System.out.println(i);
        }

        //join方法的作用:让调用这个方法的线程先执行完
        Thread t1 = new MyThread("1号线程");
        t1.start();
        t1.join();
        Thread t2 = new MyThread("2号线程");
        t2.start();
        t2.join();
        Thread t3 = new MyThread("3号线程");
        t3.start();
        Thread t4 = new MyThread("4号线程");
        t4.start();

    }
}

线程安全问题

加锁:每次只允许一个线程加锁,加锁后才能访问进入,访问完毕后自动解锁,然受其他线程才能在加锁进来

同步代码块
synchronized (同步锁){
    访问共享资源的核心代码
}
同步锁的注意事项
  • 对于当前同时执行的线程来说,同步锁必须是同一把(同一个对象),否则会出bug
  • 建议使用共享资源作为锁对象,对于实例方法建议使用this作为锁对象
  • 对于静态方法使用字节码(类名.class)对象作为锁对象
public class Account {
    private String id;//卡号
    private double money;//余额

    public Account() {
    }

    public Account(String id, double money) {
        this.id = id;
        this.money = money;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public double getMoney() {
        return money;
    }

    public void setMoney(double money) {
        this.money = money;

    }

    public void drawMoney(int i) {
        //先搞清楚是谁来取钱
        String name = Thread.currentThread().getName();
        //1判断余额是否足够
        //this 正好可以代表共享资源
        synchronized (this) {
            if(this.money>=i){
                System.out.println(name+"来取钱"+i+"成功");
                this.money-=i;
                System.out.println(name+"取钱后,余额是"+this.money);
            }else{
                System.out.println(name+"来取钱:余额不足");
            }
        }
    }
}
public class DrawThread extends Thread{
    private Account acc;
    public  DrawThread(Account acc, String name){
        super(name);
        this.acc = acc;
    }
    @Override
    public void run(){
        //取钱
        acc.drawMoney(100000);
    }
}
public class ThreadTest {
    public static void main(String[] args) {
        //创建一个账户对象
        Account acc = new Account("123456",100000);
        //2.创建两个线程分别代表小明小红,再去同一个账户中取钱
        new DrawThread(acc,"小明").start();//小明
        new DrawThread(acc,"小红").start();//小红
    }
}
同步方法

作用:把访问共享核心资源的核心方法给上锁,以此保证线程安全

  • 如果是实例方法,同步方法默认使用this作为所得对象
  • 如果方法是静态方法,同步方法默认使用类名.class作为所得对象
修饰符 synchronized 返回值类型 方法名称(形参列表){
操作共享资源的代码
}
 public synchronized void drawMoney(int i) {
        //先搞清楚是谁来取钱
        String name = Thread.currentThread().getName();

        //1判断余额是否足够
            if(this.money>=i){
                System.out.println(name+"来取钱"+i+"成功");
                this.money-=i;
                System.out.println(name+"取钱后,余额是"+this.money);
            }else{
                System.out.println(name+"来取钱:余额不足");
            }
    }
lock锁
package d4_thread_synchronized;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Account {
    private String id;//卡号
    private double money;//余额
    //创建了一个锁对象
    private final Lock lk = new ReentrantLock();

    public Account() {
    }

    public Account(String id, double money) {
        this.id = id;
        this.money = money;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public double getMoney() {
        return money;
    }

    public void setMoney(double money) {
        this.money = money;

    }

    public void drawMoney(int i) {
        //先搞清楚是谁来取钱
        String name = Thread.currentThread().getName();

        lk.lock();
        try {
            //1判断余额是否足够
            if(this.money>=i){
                System.out.println(name+"来取钱"+i+"成功");
                this.money-=i;
                System.out.println(name+"取钱后,余额是"+this.money);
            }else{
                System.out.println(name+"来取钱:余额不足");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            lk.unlock();
        }
        
    }
}

线程池

计算密集型的任务:核心线程数量 = CPU的核数 + 1

IO密集型的任务: 核心线程数量 = CPU的核数 * 2

创建线程池对象
1. 方式一:使用ExecutorService的实现类ThreadPoolExecutor自创建一个线程池对象

临时线程什么时候创建

  • 新任务提交时发现核心线程都在忙,任务队列也满了,并且还可以创建临时线程,此时才会创建临时线程

什么时候开始拒绝新任务

  • 核心线程和临时线程都在忙,任务队列也满了,新的任务过来时才会开始拒绝任务
public ThreadPoolExecutor(int corePoolSize,  //指定线程池的核心线程数量
                          int maximumPoolSize,  //指定线程池的最大线程数量
                          long keepAliveTime,  //制定临时线程的存活时间
                          TimeUnit unit,  //指定临时线程的存活的时间单位(秒,分,时,天)
                          BlockingQueue<Runnable> workQueue,  //指定线程池的任务队列
                          ThreadFactory threadFactory,  //指定线程池的线程工厂
                          RejectedExecutionHandler handler  //指定线程池的任务拒绝策略(线程都在忙,任务队列也满了的时候,新任务来了该怎么处理)
                         ) {}
ExecutorService pool = new ThreadPoolExecutor(3,5,8,TimeUnit.SECONDS,
                                              new ArrayBlockingQueue<>(4),Executors.defaultThreadFactory(),
                                              new ThreadPoolExecutor.AbortPolicy());
2. 方式二:使用Executors(线程池的工具类)调用方法返回特点的线程池对象
package d6_threadPoolExecutor;

import d1_create_thread.MyCallable;

import java.util.concurrent.*;

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

        //通过Executors创建一个线程池对象
        ExecutorService pool = Executors.newFixedThreadPool(3);

        //使用线程处理Callable任务
        Future<String> f1 = pool.submit(new d1_create_thread.MyCallable(100));
        Future f2 = pool.submit(new d1_create_thread.MyCallable(200));
        Future f3 = pool.submit(new d1_create_thread.MyCallable(300));
        Future f4 = pool.submit(new d1_create_thread.MyCallable(400));
        Future f5 = pool.submit(new MyCallable(500));

        System.out.println(f1.get());
        System.out.println(f2.get());
        System.out.println(f3.get());


    }
}
线程池处理Runnable任务
package d6_threadPoolExecutor;

import java.util.concurrent.*;

public class ExecutorTest1 {
    public static void main(String[] args) {
        ExecutorService pool = new ThreadPoolExecutor(3,5,8,TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(4),Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());

        MyRunnable target = new MyRunnable();
        pool.execute(target); //线程池会自动创建一个新线程,自动处理这个任务,自动执行
        pool.execute(target);//线程池会自动创建一个新线程,自动处理这个任务,自动执行
        pool.execute(target);//线程池会自动创建一个新线程,自动处理这个任务,自动执行
        pool.execute(target);//复用前面的线程
        pool.execute(target);//复用前面的线程
        
        pool.shutdown();//等待线程池的任务全部执行完毕后,关闭线程池
        pool.shutdownNow();//立即关闭线程池,不管任务是否执行完毕

    }
}
package d6_threadPoolExecutor;

public class MyRunnable implements Runnable{
    @Override
    public void run() {
        //描述人物任务
        System.out.println(Thread.currentThread().getName()+"输出666--");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
线程池处理Callable任务
package d6_threadPoolExecutor;

import java.util.concurrent.Callable;

//1.让这个类实现Callable接口
public class MyCallable implements Callable {
    private int n;

    public MyCallable(int n) {
        this.n = n;
    }

    //2.重写call方法
    //求1-n的和

    int sum = 0;
    @Override
    public String call() throws Exception {
        for (int i = 1; i <=n; i++) {
            sum=sum+i;
        }
        return Thread.currentThread().getName()+"线程求出了1-n的和是:"+sum;
    }
}
package d6_threadPoolExecutor;

import d1_create_thread.MyCallable;

import java.util.concurrent.*;

public class ThreadPoolTest2 {
    public static void main(String[] args) throws Exception {
        ExecutorService pool = new ThreadPoolExecutor(3,5,8, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(4), Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());

        //使用线程处理Callable任务
        Future<String> f1 = pool.submit(new MyCallable(100));
        Future f2 = pool.submit(new MyCallable(200));
        Future f3 = pool.submit(new MyCallable(300));
        Future f4 = pool.submit(new MyCallable(400));
        Future f5 = pool.submit(new MyCallable(500));

        System.out.println(f1.get());
        System.out.println(f2.get());
        System.out.println(f3.get());


    }
}
线程的生命周期

乐观锁
package d7_tx;

import java.util.concurrent.atomic.AtomicInteger;

public class MyRunnable2 implements Runnable{

    //整数修改的乐观锁:原子类实现的
    private AtomicInteger number = new AtomicInteger();
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {

                System.out.println(number.incrementAndGet());

        }
    }
}
package d7_tx;

public class Test2 {
    public static void main(String[] args) {
        //悲观锁,乐观锁原理
        //悲观锁:一上来就加锁,没有安全感,每次只能一个线程进入访问完毕后,在解锁 .线程安全,性能较差
        //乐观锁:一开始不上锁,认为是没有问题的,大家一起跑,要等出现线程安全问题才开始控制,线程安全,性能较好

        //需求:一个静态变量,100个线程,每个线程对其加100次
        Runnable target = new MyRunnable2();
        for (int i = 1; i <= 100; i++) {
            new Thread(target).start();
        }
    }
    }
悲观锁
package d7_tx;

public class MyRunnable implements Runnable{
    private int number ;//记录浏览人次
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            //悲观锁
            synchronized(this) {
                System.out.println(++number);
            }
        }
    }
}
package d7_tx;

import d7_tx.MyRunnable;

public class Test {
    public static void main(String[] args) {
        //悲观锁,乐观锁原理
        //悲观锁:一上来就加锁,没有安全感,每次只能一个线程进入访问完毕后,在解锁 .线程安全,性能较差
        //乐观锁:一开始不上锁,认为是没有问题的,大家一起跑,要等出现线程安全问题才开始控制,线程安全,性能较好

        //需求:一个静态变量,100个线程,每个线程对其加100次
        Runnable target = new MyRunnable();
        for (int i = 1; i <= 100; i++) {
            new Thread(target).start();
        }
    }
}
  • 22
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值