首页 > 其他分享 >线程的完结

线程的完结

时间:2024-02-02 20:12:06浏览次数:22  
标签:Thread void class 线程 完结 println new public

线程的状态

lambda

public class TestLambda1 {
    //3.静态类
    static class Lake2 implements Ilake{
        @Override
        public void lambda() {
            System.out.println("I Lake lambda2");
        }
    }
    public static void main(String[] args) {
        Ilake like = new Lake();
        like.lambda();
         like = new Lake2();
        like.lambda();
        class Lake3 implements Ilake{
            @Override
            public void lambda() {
                System.out.println("I Lake lambda3");
            }
        }
        like = new Lake3();
        like.lambda();
        //5.匿名内部类,没有类的名称,必须借助接口或者父类
        like = new Ilake() {
            @Override
            public void lambda() {
                System.out.println("I Lake lambda4");
            }
        };
        like.lambda();
        //6.用lambda简化
        like = ()-> {
                System.out.println("I Lake lambda5");
            };
        like.lambda();
    }

}
//1.定义一个函数式接口
interface Ilake{
    void lambda();
}
//2.实现类
class Lake implements Ilake{
    @Override
    public void lambda() {
        System.out.println("I Lake lambda");
    }
}

image-20240131130730212

image-20240201144505751

join

//测试join方法//想象插队
public class TestJoin implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
            System.out.println("线程vip来了"+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 < 1000; i++) {
            if (i==200){
                thread.join();//插队
            }
            System.out.println("main"+i);
        }
    }
}

插队

yield

public class TestYield {
    public static void main(String[] args) {
        MyYield myYield = new MyYield();
        new Thread(myYield,"A").start();
        new Thread(myYield,"B").start();
    }

}
class MyYield implements Runnable{
    @Override
    public void run() {

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

priority

//测试线程优先级
public class TestPriority {
    public static void main(String[] args) {
        System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
        MyPriority myPriority = new MyPriority();
        Thread t1 = new Thread(myPriority);
        Thread t2 = new Thread(myPriority);
        Thread t3 = new Thread(myPriority);
        Thread t4 = new Thread(myPriority);
        Thread t5 = new Thread(myPriority);
        Thread t6 = new Thread(myPriority);


        t1.start();

        t2.setPriority(10);
        t2.start();


    }

}

class MyPriority implements Runnable{

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

Daemon

//守护线程
public class TestDaemon {
    public static void main(String[] args) {
        God god = new God();
        You you = new You();
        Thread thread = new Thread(god);
        thread.setDaemon(true);
        thread.start();
        new Thread(you).start();


    }

}
//上帝
class God implements Runnable{

    @Override
    public void run() {
        while(true){
            System.out.println("上帝保佑你!");

        }
    }
}


//me
class You implements Runnable{

    @Override
    public void run() {
        for (int i = 0; i < 36500; i++) {
            System.out.println("你一生都开心活着");
        }
        System.out.println("=========goodbye!World!========");
    }
}

state

//观察测试线程的状态
public class TestState {
    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) {
                    throw new RuntimeException(e);
                }

            }
            System.out.println("///////");
        });
        //观察状态
        Thread.State state = thread.getState();
        System.out.println(state);//new
        //观察启动后
        thread.start();
        state = thread.getState();
        System.out.println(state);//run

        while (state != Thread.State.TERMINATED){
            Thread.sleep(100);
            state = thread.getState();
            System.out.println(state);
        }
    }
}

线程同步以及不安全的解决

synchronized ()锁的对象一定是变化的量,需要增删改查的量

synchronized块解决不安全

package com.zzl.Demo1;
//不安全的取钱
//两个人去取钱
public class UnsafeBank {
    public static void main(String[] args) {
        //账户
        Account account = new Account(100,"结婚基金");
        Drawing you = new Drawing(account,50,"你");
        Drawing girlFriend = new Drawing(account,100,"girlFriend");
        you.start();
        girlFriend.start();




    }
}
//账户
class Account{
    int money;
    String name;

    public Account(int money,String name) {
        this.money = money;
        this.name = name;
    }
}
//银行:模拟取款
class Drawing extends Thread{
    Account account;
    int drawingMoney;
    int nowMoney;



    public Drawing(Account account, int drawingMoney, String name){

        super(name);
        this.account = account;
        this.drawingMoney = drawingMoney;
        this.nowMoney = nowMoney;

        }
    @Override
    public void run() {
        // synchronized块解决不安全
        //锁的对象一定是变化的量,需要增删改查的量
        synchronized (account){
            //判断没有钱
            if (account.money-drawingMoney<0){
                System.out.println(Thread.currentThread().getName()+"钱不够,取不了");
                return;
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //卡内余额 = 余额 - 你取的钱
            account.money = account.money-drawingMoney;
            //你手里的前
            nowMoney = nowMoney + drawingMoney;

            System.out.println(account.name+ "余额为" +account.money);
            //Thread.currentThread().getName()= this.getName()
            System.out.println(this.getName()+"手里的钱"+nowMoney);


        }

        }

}


package com.zzl.Demo1;

import java.util.ArrayList;
import java.util.List;

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

            }).start();
        }
        try {
            Thread.sleep(1_000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(list.size());
    }
}

synchronized解决不安全

package com.zzl.Demo1;
//线程不安全
public class UnsafeBuyTicket {

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

        new Thread(station,"苦逼的我").start();
        new Thread(station,"牛逼的你们").start();
        new Thread(station,"可恶的黄牛党").start();
    }
}
class BuyTicket implements Runnable{

    //票
   private int ticketNums = 10;
   boolean flag = true;//外部停止
    @Override
    public void run() {
        //买票
        while (flag){
            buy();
        }
    }
    //synchronized解决不安全
    private synchronized void buy(){
        // 判断是否邮票
        if (ticketNums<=0){
            flag = false;
            return;
        }{
            System.out.println(Thread.currentThread().getName()+"拿到"+ticketNums--);

        }
    }
}

死锁

package com.zzl.Demo1;

public class DeadLock {
    public static void main(String[] args) {
        Makeup makeup = new Makeup(0,"灰姑凉");
        Makeup makeup2 = new Makeup(1,"白雪公主");
        makeup2.start();
        makeup.start();
    }
}
class Lipstick{

}
class Mirror{

}
class Makeup extends Thread {
    static Lipstick lipstick = new Lipstick();
    static Mirror mirror = new Mirror();
    int choice;
    String girlName;

    Makeup(int choice, String girlName) {
        this.choice = choice;
        this.girlName = girlName;
    }

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

    private void makeup() throws InterruptedException {
        if (choice == 0) {
            synchronized (lipstick) {
                System.out.println(this.girlName + "获得口红的锁");
                Thread.sleep(1000);
            }
            synchronized (mirror) {
                System.out.println(this.girlName + "获得镜子的锁");
            }
        } else {
            synchronized (mirror) {
                System.out.println(this.girlName + "获得镜子的锁");
                Thread.sleep(1000);
            }
            synchronized (lipstick) {
                System.out.println(this.girlName + "获得口红的锁");

            }
        }
    }
}

package com.zzl.Demo1;

import java.util.concurrent.locks.ReentrantLock;
//ReentrantLock可重复锁
//测试Lock锁
public class TestLock {
    public static void main(String[] args) {
        TestLock2 testLock2 = new TestLock2();
        new Thread(testLock2).start();
        new Thread(testLock2).start();
        new Thread(testLock2).start();
    }
}
class TestLock2 implements Runnable{
 int ticketNums = 10;
 //定义lock锁
    private final ReentrantLock lock = new ReentrantLock();
    @Override
    public void run() {
        while (true){
            try {
                lock.lock();//加锁
                if (ticketNums>0){
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(ticketNums--);
                }else {
                    break;
                }
            } finally {

                lock.unlock();//解锁
            }

        }
    }
}

消费者和生产者问题

package com.zzl.Demo1;

//测试:生产者消费者模拟--》利用缓冲区解决:管程法
//生产者,消费者,产品,缓冲区
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;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            container.push(new Chicken(i));
            System.out.println("生产了"+i+"kun");
        }
    }
}
class Consumer extends Thread{

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

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("消费了第"+container.pop().id+"kun");

        }
    }
}
class Chicken{
    int id;

    public Chicken(int id) {
        this.id = id;
    }
}
//缓冲区
class SynContainer{
    //需要一个容器大小
    Chicken[] chickens = new Chicken[10];
    //容器计数器
    int count = 0;
    //生产者放入产品
    public synchronized void push(Chicken chicken){
        //如果容器满了,就需要等待消费者消费
        if (count==chickens.length){
            //通知消费者消费,生产等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //如果没有满,我们就需要丢入产品
        chickens[count] = chicken;
        count++;
        this.notify();
        //可以通知消费者消费了

    }

    //消费者消费产品
    public synchronized Chicken pop(){
        //判断能否消费
        if (count==0){
            //等待生产者生产,消费者消费
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //如果可以消费
        count--;
        Chicken chicken = chickens[count];
        this.notify();
        //吃完了,通知消费者生产
        return chicken;
    }








}
package com.zzl.Demo1;
//测试生产者消费者问题2:信号灯法
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{
    //演员表演,观众等待
    //观众观看,演员等待
    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.notify();//通知唤醒
        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.notify();
        this.flag = !this.flag;
    }}

总结

package com.zzl.Demo1;

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

//1,回顾总结线程的创建
public class ThreadNew {
    public static void main(String[] args) {
        //1.继承Thread类
        new MyThread1().start();
        //2.实现Runable接口
        new Thread(new MyThread2()).start();
        //3.实现Callable接口
        FutureTask<Integer> futureTask = new FutureTask<Integer>(new MyThread3());
        new Thread(futureTask).start();//两种方法
        try {
            Integer integer = futureTask.get();
            System.out.println(integer);
        } catch (InterruptedException e) {
             e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();;
        }

    }
}
//1.继承Thread类
class MyThread1 extends Thread{
    @Override
    public void run() {
        System.out.println("MyThread1");
    }
}
//2.实现Runable接口
class MyThread2 implements Runnable{

    @Override
    public void run() {
        System.out.println("MyThread2");
    }
}
//3.实现Callable接口
class MyThread3 implements Callable{

    @Override
    public Integer call() throws Exception {
        System.out.println("MyThread3");
        return 100;
    }
}

标签:Thread,void,class,线程,完结,println,new,public
From: https://www.cnblogs.com/zzl990110/p/18003762

相关文章

  • 深入浅出Java多线程(六):Java内存模型
    引言大家好,我是你们的老伙计秀才!今天带来的是[深入浅出Java多线程]系列的第六篇内容:Java内存模型。大家觉得有用请点赞,喜欢请关注!秀才在此谢过大家了!!!在并发编程中,有两个关键问题至关重要,它们是线程间通信机制和线程间同步控制。线程间通信机制线程间通信是指在一个多线程程序......
  • 深入浅出Java多线程(八):volatile
    引言大家好,我是你们的老伙计秀才!今天带来的是[深入浅出Java多线程]系列的第八篇内容:volatile。大家觉得有用请点赞,喜欢请关注!秀才在此谢过大家了!!!在当今的软件开发领域,多线程编程已经成为提高系统性能和响应速度的重要手段。Java作为广泛应用的多线程支持语言,其内存模型(JMM)设计巧妙......
  • js处理事件:异步处理事件与线程,使用队列按序执行,事件广播,事件bus,事件监听,变量监听,动态
    js处理事件:异步处理事件与线程,使用队列按序执行,事件广播,事件bus,事件监听,变量监听,动态执行,父子通信在Vue3中,你可以使用以下方法来处理异步事件、线程、队列执行、事件广播、事件总线、事件监听、变量监听、动态执行和父子通信:1.异步处理事件:可以使用async/await或Promise......
  • 线程状态
    线程状态6种:start();Runaune可运行,销毁获取锁失败,进入blocked-阻塞,获取锁成功后等待:获得锁wait(long)等待,时间到或notify()时间到sleep(),时间到回到可运行代码演示:getStatus获取线程信息()函数式编程线程内源代码操作系统5种正在执行cup叫执行,没分配到你叫就绪,(分配......
  • 进程与线程的概念
    想必大家在使用计算机时都知道可以同时打开多个软件,比如Word、VisualStudio、QQ音乐。通常在办公的时候或者程序员在编程的时候,一边开发软件,一边听着歌曲。其实,这是操作系统为这三款不同的程序开辟了彼此独立的内存,以保证它们的良好运行。每一个程序都代表一个进程(Process)。进程中......
  • ConcurrentHashMap的线程安全
    ConcurrentHashMap是怎么做到线程安全的?   get方法如何线程安全地获取key、value?   put方法如何线程安全地设置key、value?   size方法如果线程安全地获取容器容量?   底层数据结构扩容时如果保证线程安全?   初始化数据结构时如果保证线程安全?ConcurrentHashMap......
  • concurrent hashmap put操作的线程安全
     减小锁粒度:将Node链表的头节点作为锁,若在默认大小16情况下,将有16把锁,大大减小了锁竞争(上下文切换),就像开头所说,将串行的部分最大化缩小,在理想情况下线程的put操作都为并行操作。同时直接锁住头节点,保证了线程安全Unsafe的getObjectVolatile方法:此方法确保获取到的值为最新  ......
  • ConcurrentHashMap是如何实现线程安全的
     但是又为何需要学习ConcurrentHashMap?用不就完事了?我认为学习其源码有两个好处:更灵活的运用ConcurrentHashMap欣赏并发编程大师DougLea的作品,源码中有很多值得我们学习的并发思想,要意识到,线程安全不仅仅只是加锁ConcurrentHashMap是怎么做到线程安全的?   get方法如何线......
  • 【操作系统和计网从入门到深入】(八)线程
    复习八·线程1.如何理解线程只要满足,比进程轻量化,cpu内所有线程资源共享,创建维护成本更低等要求,就能叫线程。不同的OS实现方式不同,下面这个是Linux特有的方案。Linux没有给线程重新设计数据结构!什么叫做进程?pcb+地址空间+页表CPU调度的基本单位:线程!2.开始使用pthre......
  • 深入浅出Java多线程(五):线程间通信
    引言大家好,我是你们的老伙计秀才!今天带来的是[深入浅出Java多线程]系列的第五篇内容:线程间通信。大家觉得有用请点赞,喜欢请关注!秀才在此谢过大家了!!!在现代编程实践中,多线程技术是提高程序并发性能、优化系统资源利用率的关键手段。Java作为主流的多线程支持语言,不仅提供了丰富的......