java多线程的三种创建方式及常用方法和锁使用

本文详细介绍了Java中创建线程的三种方法:继承Thread类、实现Runnable接口和实现Callable接口。通过实例展示了线程操作同一资源时的安全问题,并讲解了线程的常用方法,如sleep、yield、join和线程状态的获取。此外,还探讨了线程的优先级、守护线程、线程同步机制、死锁和线程通信方法,以及线程池的概念和优势。
摘要由CSDN通过智能技术生成

概念

process 进程 thread线程
程序是静态的,是指令和数据的有序结合
进程是执行程序的一次过程是系统资源分配的单位
线程是CPU执行和调度的单位
.
java默认有两个线程:main和gc垃圾回收
.
java是无法开启线程的,只能调用本地底层的c++
private native void start0();

创建线程的三种方法

方法一:继承thread类,重写run方法,main主函数调用start开启线程

(不建议使用,OOP单继承局限性)

//继承thread类
public class thread extends Thread{

    @Override
    //重写run方法
    public void run() {
        for (int i = 0; i<200; i++){
            System.out.println("这是run线程"+i);
        }
    }

    public static void main(String[] args) {

        thread thread1 = new thread();
        //调用start
        thread1.start();

        for (int i = 0;i<200;i++){
            System.out.println("这是main线程"+i);
        }
    }

}

方法二:实现runnable接口(其实上面的thread也实现了这个接口),重写run方法,main主函数调用start开启线程

(建议使用,避免单继承局限性,灵活使用,方便同一个对象被多个线程使用)

//实现runnable接口
public class runn implements Runnable{
    @Override
    //run方法线程体
    public void run() {
        for (int i = 0; i<200; i++){
            System.out.println("这是run线程"+i);
        }
    }

    public static void main(String[] args) {

        //创建runnable接口实现类对象
        runn runn = new runn();

        //创建线程对象
        Thread thread = new Thread(runn);
        
        //通过线程对象开启线程(代理)
        thread.start();

        //其实上面两句等价于
         new Thread(runn).start();

        for (int i = 0;i<200;i++){
            System.out.println("这是main线程"+i);
        }
    }

}

例子1:多个线程操作同一个资源的情况下,线程是不安全的,数据紊乱。

public class unsafe implements Runnable{

    private int ticket= 10;

    @Override
    public void run() {
            while (true){
                if (ticket<=0){
                    break;
                }
                try {
                    //模拟延迟
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName()+ "拿到了第" + ticket-- + "张票");
            }
    }

    public static void main(String[] args) {
        unsafe unsafe = new unsafe();

        new Thread(unsafe,"小明").start();
        new Thread(unsafe,"小蓝").start();
        new Thread(unsafe,"小黄").start();
    }
}

输出结果为

在这里插入图片描述

例子2:龟兔赛跑

public class rabbit implements Runnable{

    private static String winner;

    @Override
    public void run() {
     for (int i = 0;i<=100;i++){

         //模拟兔子休息
         if (Thread.currentThread().getName().equals("兔子")){
             try {
                 Thread.sleep(1);
             } catch (InterruptedException e) {
                 e.printStackTrace();
             }
         }

         //判断比赛是否结束
         boolean flag = gameOver(i);
         if (flag){
             break;
         }

         System.out.println(Thread.currentThread().getName()+"跑了"+i+"步");
     }
    }

    private boolean gameOver(int steps){
        //判断是否有胜利者
        if (winner!= null){
            return true;
        }else {
            if (steps>=100){
                winner = Thread.currentThread().getName();
                System.out.println("winner is "+winner);
                return true;
            }
        }

        return false;
    }

    public static void main(String[] args) {
        rabbit rabbit = new rabbit();

        new Thread(rabbit,"乌龟").start();
        new Thread(rabbit,"兔子").start();
    }
}

方法三:实现callable接口,需要返回值类型,重写call方法(需要抛出异常)

public class call1 implements Callable {
    @Override
    public Object call() throws Exception {
        for (int x = 0; x < 100; x++) {
            System.out.println(Thread.currentThread().getName() + ":" + x);
        }
        return null;
    }

    public static void main(String[] args) {

        //创建线程池对象
        ExecutorService pool = Executors.newFixedThreadPool(2);

        //提交任务
        pool.submit(new call1());
        pool.submit(new call1());

        //关闭线程池
        pool.shutdown();

    }
}

线程的一些常用方法

线程的停止

建议让线程自己停下来
可以使用一个标志位来停止变量当 flag=false 时,则终止线程
不要使用stop,destory等过时方法或JDK不建议使用的方法

public class testStop implements Runnable{

    private boolean flag=true;

    @Override
    public void run() {
        int i =0;
        while (flag){
            System.out.println("线程在run...."+i);
        }

    }


    public void stop(){
        this.flag=false;
    }

    public static void main(String[] args) {

        testStop stop = new testStop ();

        new Thread(stop).start();

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

            System.out.println("main线程在run...."+i);

            if (i == 900){
                stop.stop();
                System.out.println("线程停止了");
            }
        }

    }
}

线程休眠——sleep

可以指定当前线程阻塞的毫秒数,所以可以模拟网络延时,倒计时等
日常可以用sleep放大线程一些问题的发生性
每个对象都有一个锁,sleep不会释放锁

模拟网络延时

别说我偷懒,这里确实用到了sleep

public class TestSleep1 implements Runnable {


        private int ticket = 10;

        @Override
        public void run () {
        while (true) {
            if (ticket <= 0) {
                break;
            }
            try {
                //模拟延迟
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "拿到了第" + ticket-- + "张票");
        }
    }

        public static void main (String[]args){
        com.andrew.thread.unsafe3 unsafe = new com.andrew.thread.unsafe3();

        new Thread(unsafe, "小明").start();
        new Thread(unsafe, "小蓝").start();
        new Thread(unsafe, "小黄").start();
    }
    

}

使用sleep每隔一秒获取系统时间

public class TestSleep2 {

    //模拟倒计时
    public static void tenDown() throws InterruptedException {
        int num = 10;
        while (true){
            Thread.sleep(1000);
            System.out.println(num--);
            if (num<=0){
                break;
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Date date = new Date(System.currentTimeMillis());//获取当前时间

        while (true){
            Thread.sleep(1000);
            System.out.println(new SimpleDateFormat("HH:mm:ss").format(date));
            date = new Date(System.currentTimeMillis());//更新当前时间
        }

    }

}

线程礼让——yield

线程礼让即A从运行状态,又变成就绪状态,这时候A和B又是同一起跑线继续跑
所以,线程礼让不一定成功

public class TestYield {

    public static void main(String[] args) {
        MyYield m =new MyYield();

        new Thread(m,"A").start();
        new Thread(m,"B").start();
    }

}


class MyYield implements Runnable{

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"线程开始执行");
        Thread.yield();//线程礼让
        System.out.println(Thread.currentThread().getName()+"线程停止执行");
    }
}

线程强制执行——join

会造成线程阻塞

public class TestJoin implements Runnable{


    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("Join插队"+i+"次");
        }
    }

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

        TestJoin testJoin = new TestJoin();

        Thread thread = new Thread(testJoin);
        thread.start();

        for (int i = 0; i < 100; i++) {
            System.out.println("main线程运行"+i+"次");
            if (i==50){
                thread.join();
            }
        }

    }
}

观测线程状态——getState()

要注意线程死了之后无法再start()

public class TestLook {

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("线程结束");
        });
        
        //观察状态
        Thread.State state = thread.getState();
        //NEW
        System.out.println(state);

        //观察启动后
        //启动线程
        thread.start();
        state = thread.getState();
        //RUN
        System.out.println(state);

        //只要不终止,就一直输出状态
        while (state != Thread.State.TERMINATED){
            Thread.sleep(100);
            //更新线程状态
            state = thread.getState();
            //输出状态
            System.out.println(state);
        }
    }
}

线程的优先级——setPriority

可以看到优先级高的先执行,但是这其实并不是绝对的,也有少部分不会这样(性能倒置)

public class TestPriority {


    public static void main(String[] args) {
        System.out.println(Thread.currentThread().getName()+"--->"+Thread.currentThread().getPriority());

        MyPriority myPriority = new MyPriority();


        Thread a1 = new Thread(myPriority);
        Thread a2 = new Thread(myPriority);
        Thread a3 = new Thread(myPriority);
        Thread a4 = new Thread(myPriority);

        a1.start();

        a2.setPriority(3);
        a2.start();

        a3.setPriority(Thread.MAX_PRIORITY);
        a3.start();

        a4.setPriority(7);
        a4.start();

    }
}


class MyPriority implements Runnable{

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"--->"+Thread.currentThread().getPriority());
    }
}

结果

main--->5
Thread-2--->10
Thread-0--->5
Thread-3--->7
Thread-1--->3

守护线程——Daemon

线程分为用户线程和守护线程
虚拟机会确保用户进程(main…)执行完毕
虚拟机不会确保守护进程(gc…)执行完毕

public class TestDaemon {

    public static void main(String[] args) {
        Daemon daemon = new Daemon();
        Common common = new Common();

        Thread thread = new Thread(daemon);
        //默认是false
        thread.setDaemon(true);
        thread.start();

        new Thread(common).start();
    }

}

//守护线程
class Daemon implements Runnable{

    @Override
    public void run() {
        while (true){
            System.out.println("我是守护线程");
        }
    }
}

//用户线程
class Common implements Runnable{

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("我是用户线程---》"+i);
        }
        System.out.println("我结束了");
    }
}

线程同步机制

多个线程访问同一个对象就会产生队列,为了保证线程安全就产生了锁(synchronized)。
锁带来了安全,也带来了不便
1.一个线程持有锁会导致其他需要此锁的线程挂起
2.在多线程竞争下﹐加锁﹐释放锁会导致比较多的上下文切换和调度延时,引起性能问题;
3.如果一个优先级高的线程等待一个优先级低的线程释放锁会导致优先级倒置,引起性能问题.

列举不安全案例

举例1

每个线程都在自己的工作内存内交互,内存控制不当会造成数据不一致

//不安全买票
public class BuyTicket {

    public static void main(String[] args) {

        Buy buy = new Buy();

        new Thread(buy,"一号").start();
        new Thread(buy,"二号").start();
        new Thread(buy,"三号").start();
    }
}

class Buy implements Runnable{

    private int ticket=10;
    boolean flag=true;

    @Override
    public void run() {
        while (flag){
            try {
                judge();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private void judge() throws InterruptedException {
        if (ticket == 0){
            flag = false;
            return;
        }

        Thread.sleep(10);
        System.out.println(Thread.currentThread().getName()+"拿到了第"+ticket--+"张票");
    }

}

举例二

两个线程操作同一个位置,会覆盖,导致线程变少,所以这个输出结果不是一万,而是小于一万

//线程不安全的集合
public class UnsafeList {
    public static void main(String[] args) {
        List<String> list = new ArrayList<String>();
        for (int i = 0; i < 10000; i++) {
            new Thread(() -> {
                list.add(Thread.currentThread().getName());
            }).start();
        }
        System.out.println(list.size());
    }
}

锁的常见使用和问题

同步方法

只要在方法上加锁就行

//安全买票
public class BuyTicket {

    public static void main(String[] args) {

        Buy buy = new Buy();

        new Thread(buy,"一号").start();
        new Thread(buy,"二号").start();
        new Thread(buy,"三号").start();
    }
}

class Buy implements Runnable{

    private int ticket=10;
    boolean flag=true;

    @Override
    public void run() {
        while (flag){
            try {
                judge();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

	//在这里加
    private synchronized void judge() throws InterruptedException {
    
    	//判断是否有票
        if (ticket <= 0){
            flag = false;
            return;
        }

        Thread.sleep(10);
        System.out.println(Thread.currentThread().getName()+"拿到了第"+ticket--+"张票");
    }

}

同步块

默认锁的是this
锁的对象就是变化的量,即需要增删改的对象

//线程安全的集合
public class test {
        public static void main(String[] args) {
            List<String> list = new ArrayList<String>();
            for (int i = 0; i < 10000; i++) {
                new Thread(() -> {
                    synchronized (list){
                        list.add(Thread.currentThread().getName());
                    }
                }).start();
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(list.size());
        }

}

死锁

产生死锁的四个条件
互斥条件: 一个资源每次只能被一个进程使用。
请求与保持条件: 一个进程因请求资源而阻塞时,对已获得的资源保持不放。
不剥夺条件: 进程已获得的资源,在末使用完之前,不能强行剥夺。
循环等待条件: 若干进程之间形成一种头尾相接的循环等待资源关系。
大白话就是 我有苹果我想吃梨 你有梨你想吃苹果 但是双手都想让对方先给,自己再给 就卡死了

Lock锁

显式加锁,释放锁
如果同步代码有异常,要将 lock.unlock(); 写入finally语句块
ReentrantLock(可重复锁)实现了Lock

public class test {

        public static void main(String[] args) {

            com.andrew.syn.Buy1 buy = new com.andrew.syn.Buy1();

            new Thread(buy,"一号").start();
            new Thread(buy,"二号").start();
            new Thread(buy,"三号").start();
        }
    }

    class Buy1 implements Runnable{

        private int ticket=10;
        boolean flag=true;
        private final ReentrantLock lock = new ReentrantLock();

        @Override
        public void run() {
            while (flag){
                try {
                    lock.lock();
                    judge();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally{
                    lock.unlock();
                }


            }
        }

        private void judge() throws InterruptedException {
            if (ticket == 0){
                flag = false;
                return;
            }

            Thread.sleep(10);
            System.out.println(Thread.currentThread().getName()+"拿到了第"+ticket--+"张票");
        }

    }

Lock 锁和synchronized 锁对比

Lock是显式锁(手动开启和关闭锁,别忘记关闭锁) synchronized是隐式锁,出了作用域自动释放
.
Lock只有代码块锁,synchronized有代码块锁和方法锁
.
使用Lock锁,JVM将花费较少的时间来调度线程,性能更好。并且具有更好的扩展性(提供更多的子类)
.
优先使用顺序: Lock >同步代码块(已经进入了方法体,分配了相应资源)>同步方法(在方法体之外)

线程通信

常用方法wait,notify等

在这里插入图片描述

wait和sleep的区别

1.他们属于不同的类
wait–》object
sleep–》Thread
.
2.wait会释放锁,sleep不会释放锁
.
3.位置不同
wait必须在同步代码块中
sleep可以在任何地方

管程法

利用缓冲区解决

package com.andrew.gaoji;

/**
 * 协作模型:生产者消费者实现方式一:管程法
 * 借助缓冲区
 *
 * @author
 */
//实例:模拟生产馒头
public class TestPC {
    public static void main(String[] args) {
        //缓冲区
        SynContainer container = new SynContainer();
        //生产者
        new Productor(container).start();
        //消费者
        new Consumer(container).start();
    }
}

//生产者
class Productor extends Thread {
    SynContainer container;

    public Productor(SynContainer container) {
        this.container = container;
    }

    public void run() {
        //生产
        for (int i = 0; i < 100; i++) {
            System.out.println("生产-->" + i + "个馒头");
            container.push(new Steamedbun(i));
        }
    }
}

//消费者
class Consumer extends Thread {
    SynContainer container;

    public Consumer(SynContainer container) {
        this.container = container;
    }

    public void run() {
        //消费
        for (int i = 0; i < 100; i++) {
            System.out.println("消费-->" + container.pop().id + "个馒头");
        }
    }
}

//缓冲区
class SynContainer {
    Steamedbun[] buns = new Steamedbun[10]; //存储容器
    int count = 0; //计数器

    //存储 生产
    public synchronized void push(Steamedbun bun) {
        //何时能生产  容器存在空间
        //不能生产 只有等待
        if (count == buns.length) {
            try {
                this.wait(); //线程阻塞  消费者通知生产解除
            } catch (InterruptedException e) {
            }
        }
        //存在空间 可以生产
        buns[count] = bun;
        count++;
        //存在数据了,可以通知消费了
        this.notifyAll();
    }

    //获取 消费
    public synchronized Steamedbun pop() {
        //何时消费 容器中是否存在数据
        //没有数据 只有等待
        if (count == 0) {
            try {
                this.wait(); //线程阻塞  生产者通知消费解除
            } catch (InterruptedException e) {
            }
        }
        //存在数据可以消费
        count--;
        Steamedbun bun = buns[count];
        this.notifyAll(); //存在空间了,可以唤醒对方生产了
        return bun;
    }
}

//馒头
class Steamedbun {
    int id;

    public Steamedbun(int id) {
        this.id = id;
    }
}

信号灯法

用标志位解决
需要注意的是 wait 最好用 while 来判断而不是if,我这里其实有点不规范

//信号灯法
public class TestPC2 {

    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{
    //演员表演,观众等待  T
    //观众观看,演员等待  F
    //表演节目
    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;
    }

}

线程池

提前创建好多个线程,放入线程池中,使用时直接获取,使用完放回池中可以避免频繁创建销毁、实现重复利用。

好处:
提高响应速度(减少了创建新线程的时间)
降低资源消耗(重复利用线程池中线程,不需要每次都创建)
便于线程管理(……)
1.corePoolSize:核心池的大小
2.maximumPoolSize:最大线程数
3.keepAliveTime:线程没有任务时最多保持多长时间后会终止

public class TestPool {

    public static void main(String[] args) {

        //创建服务,创建线程池
        //newFixedThreadPool参数为线程池大小
        ExecutorService service1 = Executors.newFixedThreadPool(10);

        service1.execute(new MyThread());
        service1.execute(new MyThread());
        service1.execute(new MyThread());
        service1.execute(new MyThread());

        //关闭连接
        service1.shutdown();
    }

}

class MyThread implements Runnable{

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Andrew0219

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值