首页 > 其他分享 >多线程

多线程

时间:2022-10-25 03:55:05浏览次数:42  
标签:Thread void System println new 多线程 public

多线程

线程创建--继承Thread类

不推荐使用:避免OOP单继承局限性

package com.beijing.xiaowen.multithreading;


//创建线程方式一:继承Thread类,重写run方法,调用start开启线程

//总结:线程开启不一定立即执行,由cpu调度执行
public class TestThread extends Thread{
    @Override
    public void run(){
        //run方法线程体
        for (int i = 0; i < 100; i++) {
            System.out.println("run");
        }
    }
    public static void main(String[] args) {
        TestThread testThread = new TestThread();
        testThread.start();;

        for (int i = 0; i < 100; i++) {
            System.out.println("主方法");
        }
    }
}

实现Runnable接口

推荐使用:避免单继承局限性,灵活方便,方便同一个对象被多个线程使用

package com.beijing.xiaowen.multithreading;

//创建现成的第二种方法:实现 Runnable
public class TestThread2 implements Runnable {

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("实现Runnable");
        }
    }

    public static void main(String[] args) {
        TestThread2 testThread2 = new TestThread2();
        new Thread(testThread2).start();
        for (int i = 0; i < 100; i++) {
            System.out.println(i);
        }
    } 
}

多个对象使用同一个线程的时候。会造成资源紊乱

package com.beijing.xiaowen.multithreading;

public class TestThread3 implements Runnable {

   private int ticks = 10;

    @Override
    public void run() {
        while (true){
            if (ticks<=0){
                break;
            }
            //模拟延时
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"->>"+"拿到了:"+ticks--);
        }
    }

    public static void main(String[] args) {
        TestThread3 testThread3 = new TestThread3();
        new Thread(testThread3,"jay").start();
        new Thread(testThread3,"ming").start();
        new Thread(testThread3,"uzi").start();
    }
}

龟兔赛跑

package com.beijing.xiaowen.multithreading;

public class TestThread4 implements Runnable{

    private String winner;

    @Override
    public void run() {

        for (int i = 0; i <= 100; i++) {
            //模拟老六休息
            if (Thread.currentThread().getName().equals("老六") && i%10==0){
                try {
                    Thread.sleep(5);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //判断比赛是否结束
            boolean flag = game(i);

            //比赛结束,停止程序
            if (flag){
                break;
            }

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

    public boolean game(int steps){
        if (winner != null){
             return true;
        }
        if (steps>=100){
            winner=Thread.currentThread().getName();
            System.out.println("winner is"+winner);
            return true;
        }
        return false;
    }
    public static void main(String[] args) {
        TestThread4 testThread4 = new TestThread4();
        new Thread(testThread4,"杨明").start();
        new Thread(testThread4,"老六").start();
    }
}

实现Callable接口

package com.beijing.xiaowen.multithreading;

import java.util.concurrent.*;

//创建线程第三种方法:实现CallAble接口
public class TestThead5 implements Callable<Boolean> {
    @Override
    public Boolean call() throws Exception {

        return true;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        TestThead5 testThead5 = new TestThead5();
        TestThead5 testThead51 = new TestThead5();
        TestThead5 testThead52 = new TestThead5();
        
        //创建执行服务
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        
        //提交执行
        Future<Boolean> submit = executorService.submit(testThead5);
        Future<Boolean> submit1 = executorService.submit(testThead51);
        Future<Boolean> submit2 = executorService.submit(testThead52);
        
        //获取结果
        Boolean aBoolean = submit.get();
        Boolean aBoolean1 = submit1.get();
        Boolean aBoolean2 = submit2.get();
        
        //关闭服务
        executorService.shutdownNow();
    }
}

静态代理

package com.beijing.xiaowen.multithreading;

public class StaticProxy {
    public static void main(String[] args) {
        new Company(new You()).happyMarry();

        //对比线程
        new Thread(()->System.out.println("xxx")).start();
    }
}

interface Marry{
    void happyMarry();
}

//真实角色,you
class You implements Marry{

    @Override
    public void happyMarry() {
        System.out.println("婚姻是爱情的坟墓");
    }
}

//代理角色
class Company implements Marry{

    private Marry marry;

    public Company(Marry marry) {
        this.marry = marry;
    }

    @Override
    public void happyMarry() {
        before();
        this.marry.happyMarry();
        after();
    }

    private void after() {
        System.out.println("baby");
    }

    private void before() {
        System.out.println("loving");
    }
}

lambda

一个接口中,只有一个方法,则就是函数式接口

package com.beijing.xiaowen.lambda;

//代码推导lambda表达式
public class Test01 {

    //3、静态内部类
    static class NewHello2 implements Hello {
        @Override
        public void test0190() {
            System.out.println("222");
        }

        public static void main(String[] args) {
            Hello hello = new NewHello();
            hello.test0190();

            hello = new NewHello2();
            hello.test0190();
            //4、局部内部类
            class NewHello3 implements Hello {

                @Override
                public void test0190() {
                    System.out.println("333");
                }

            }

            hello = new NewHello3();
            hello.test0190();

            //5、匿名内部类,没有类的名称,必须借助接口或者父类
            hello = new Hello() {
                @Override
                public void test0190() {
                    System.out.println("444");
                }
            };
            hello.test0190();

            //6、用lambda简化
            hello = () -> {
                System.out.println("555");
            };
            hello.test0190();
        }
    }
}

//1、定义一个函数式接口
interface Hello{
    void test0190();
}

//2、实现类
class NewHello implements Hello {

    @Override
    public void test0190() {
        System.out.println("111");
    }

}

简化lambda

package com.beijing.xiaowen.lambda;

import java.util.function.IntConsumer;

//简化lambda代码
public class Test02 {
    public static void main(String[] args) {
        ILove love = new Love();
        love.test01(1);
        //1、以往
        love = new Love() {
            @Override
            public void test01(int a) {
                System.out.println(a);
            }
        };
        love.test01(2);
        //2、简化1
        love = (int a) -> {
            System.out.println(a);
        };
        love.test01(3);
        //3、去掉参数类型
        love = (a) -> {
            System.out.println(a);
        };
        love.test01(4);
        //4、去掉()
        love = a -> {
            System.out.println(a);
        };
        love.test01(5);
        //5、去掉{}
        love = a -> System.out.println(a);
        love.test01(6);

    }

    /*
    * 总结:
    * lambda表达式只能有一行代码的情况下,才能简化一行。如果多行,则只能用代码块包裹
    * 前提是函数式接口
    * 多个参数也可以去掉参数类型。要去掉都去掉
    * */
}

interface ILove{
    void test01(int a);
};

class Love implements ILove{

    @Override
    public void test01(int a) {
        System.out.println(a);
    }
}

线程的状态

停止线程

package com.beijing.xiaowen.multithreading;

//测试stop
//1.建议线程正常停止 -》利用循环从次数,不建议死循环
//2.建议使用标志位 -》 设置一个标志位
//3.不要使用stop或destory等过时或者JDK不建议使用的方法
public class TestStop implements Runnable{

    private boolean flag = true;
    @Override
    public void run() {
        int i = 0;
        while (flag){
            System.out.println("Thread run"+i++);
        }
    }

    public static void main(String[] args) {
        TestStop testStop = new TestStop();
        new Thread(testStop).start();
        for (int i = 0; i < 500; i++) {
            System.out.println("main"+i);
            if (i==400){
                testStop.stopThread();
                System.out.println("停止了");
            }

        }
    }

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

线程休眠

模拟延时,主要是为了问题放大化

每一个对象都有一个锁,sleep不会释放锁

package com.beijing.xiaowen.multithreading;

import java.text.SimpleDateFormat;
import java.util.Date;

public class TestSleep {
    public static void main(String[] args) throws InterruptedException {
//        tenDown();


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

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

线程礼让

线程礼让不一定成功,主要看cpu调度

package com.beijing.xiaowen.multithreading;

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

class myYield implements Runnable{

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"11111");
        Thread.yield();
        System.out.println(Thread.currentThread().getName()+"22222");
    }
}

线程强制执行

package com.beijing.xiaowen.multithreading;

public class TestJoin implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 500; 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 < 200; i++) {
            if (i==100){
                thread.join();
            }
            System.out.println("main"+i);
        }
    }
}

线程状态检测

package com.beijing.xiaowen.multithreading;

public class TestStatus {
    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();
        System.out.println(state);

        thread.start();
        state  = thread.getState();
        System.out.println(state);

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

线程的优先级

优先级只是意味着获得调度的概率高。主要还是看cpu的调度

package com.beijing.xiaowen.multithreading;

public class TestPriority {
    public static void main(String[] args) {
        System.out.println(Thread.currentThread().getName()+"--->"+Thread.currentThread().getPriority());
        MyPriority myPriority = new MyPriority();
        Thread thread = new Thread(myPriority);
        Thread thread1 = new Thread(myPriority);
        Thread thread2 = new Thread(myPriority);
        Thread thread3 = new Thread(myPriority);
        thread.start();
        thread1.setPriority(2);
        thread1.start();
        thread2.setPriority(6);
        thread2.start();
        thread3.setPriority(Thread.MAX_PRIORITY);
        thread3.start();
    }
}
class MyPriority implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"--->"+Thread.currentThread().getPriority());
    }
}

守护线程

package com.beijing.xiaowen.multithreading;

public class TestDaemon {
    public static void main(String[] args) {
        God god = new God();
        We we = new We();
        Thread thread = new Thread(god);
        thread.setDaemon(true);//默认都是false
        thread.start();

        new Thread(we).start();
    }
}

class God implements Runnable{

    @Override
    public void run() {
        while (true){
            System.out.println("god 保佑 you");
        }
    }
}

class We implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 36500; i++) {
            System.out.println("happy everyday");
        }
        System.out.println("bye world!!!");
    }
}

线程的同步

形成条件:队列+锁

三大不安全例子:

1、不安全买票:

package com.beijing.xiaowen.syc;

//不安全买票
public class Demo01 {
    public static void main(String[] args) {
        BuyTicket buyTicket = new BuyTicket();
        new Thread(buyTicket,"aa").start();
        new Thread(buyTicket,"bb").start();
        new Thread(buyTicket,"cc").start();
    }
}

class BuyTicket implements Runnable{
    private int ticketNum = 10;
    boolean flag = true;
    @Override
    public void run() {
        while (flag){
            try {
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void buy() throws InterruptedException {
        if (ticketNum<=0){
            flag = false;
            return;
        }
        Thread.sleep(100);
        System.out.println(Thread.currentThread().getName()+"拿到"+ticketNum--);
    }
}

2、不安全取钱

package com.beijing.xiaowen.syc;

public class Demo02 {
    public static void main(String[] args) {
        Account account = new Account(100,"账户");
        Drawing boy = new Drawing(account, 50, "boy");
        Drawing girl = new Drawing(account, 100, "girl");
        boy.start();
        girl.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 drawMoney;
    //手里多少钱
    int nowMoney;

    public Drawing(Account account,int drawMoney,String name){
        super(name);
        this.account = account;
        this.drawMoney = drawMoney;
    }

    @Override
    public void run() {
        if (account.money - drawMoney < 0){
            System.out.println(this.getName()+"余额不足");
            return;
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        account.money = account.money - drawMoney;
        nowMoney = nowMoney+drawMoney;
        System.out.println(account.name+"余额为:"+account.money);
        System.out.println(this.getName()+"手里的钱"+nowMoney);
    }
}

3、不安全集合

package com.beijing.xiaowen.syc;

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

public class Demo03 {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        for (int i = 0; i < 1000; i++) {
            new Thread(()->{
                list.add(Thread.currentThread().getName());
            }).start();
        }
        System.out.println(list.size());
    }
}

同步方法和代码块

synchronized 锁变化的量(增删改查的对象),默认锁的是 this

package com.beijing.xiaowen.syc;

//不安全买票
public class Demo01 {
    public static void main(String[] args) {
        BuyTicket buyTicket = new BuyTicket();
        new Thread(buyTicket,"aa").start();
        new Thread(buyTicket,"bb").start();
        new Thread(buyTicket,"cc").start();
    }
}

class BuyTicket implements Runnable{
    private int ticketNum = 10;
    boolean flag = true;
    @Override
    public void run() {
        while (flag){
            try {
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    //synchronized 同步方法,锁的是this
    public synchronized void buy() throws InterruptedException {
        if (ticketNum<=0){
            flag = false;
            return;
        }
        Thread.sleep(100);
        System.out.println(Thread.currentThread().getName()+"拿到"+ticketNum--);
    }
}

package com.beijing.xiaowen.syc;

public class Demo02 {
    public static void main(String[] args) {
        Account account = new Account(100,"账户");
        Drawing boy = new Drawing(account, 50, "boy");
        Drawing girl = new Drawing(account, 100, "girl");
        boy.start();
        girl.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 drawMoney;
    //手里多少钱
    int nowMoney;

    public Drawing(Account account,int drawMoney,String name){
        super(name);
        this.account = account;
        this.drawMoney = drawMoney;
    }

    @Override
    public void run() {
        synchronized (account){
            if (account.money - drawMoney < 0){
                System.out.println(this.getName()+"余额不足");
                return;
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            account.money = account.money - drawMoney;
            nowMoney = nowMoney+drawMoney;
            System.out.println(account.name+"余额为:"+account.money);
            System.out.println(this.getName()+"手里的钱"+nowMoney);
        }

    }
}

package com.beijing.xiaowen.syc;

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

public class Demo03 {
    public static void main(String[] args) throws InterruptedException {
        List<String> list = new ArrayList<>();
        for (int i = 0; i < 1000; i++) {
            new Thread(()->{
                synchronized (list){
                    list.add(Thread.currentThread().getName());
                }


            }).start();
        }

        Thread.sleep(3000);
        System.out.println(list.size());
    }
}

测试JUC安全类型的集合 CopyOnWriteArrayList

package com.beijing.xiaowen.syc;

import java.util.concurrent.CopyOnWriteArrayList;

//测试JUC安全的集合
public class Test01 {
    public static void main(String[] args) throws InterruptedException {
        CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
        for (int i = 0; i < 1000; i++) {
            new Thread(() ->{
                list.add(Thread.currentThread().getName());
            }).start();
        }

        Thread.sleep(3000);

        System.out.println(list.size());
    }
}

死锁

产生死锁的四个必要条件:

1.互斥条件:一个资源每次只能被一个进程使用

2.请求与保持条件:一个进程因请求资源而堵塞时,对已获得的资源保持不放

3.不剥夺条件:进程已获得的资源,在未使用完之前,不能强行剥夺

4.循环等到条件:若干进程之间形成一种头尾相接的循环等待资源关系

上面破坏任意一个,即可避免死锁发生

 package com.beijing.xiaowen.lock;

public class DeadLock {
    public static void main(String[] args) {
        MakeUp makeUp = new MakeUp(0, "001");
        MakeUp makeUp1 = new MakeUp(1, "002");
        makeUp.start();
        makeUp1.start();
    }
}
class Lipstick{}

class Mirror{}

class MakeUp extends Thread{
    //需要的资源只有一份,用static保证
    static  Lipstick lipstick = new Lipstick();
    static Mirror mirror = new Mirror();
    int choice;
    String name;
    MakeUp(int choice,String name){
        this.choice= choice;
        this.name = name;
    }
    @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.getName()+"获得口红的锁");
                Thread.sleep(1000);
                synchronized (mirror){
                    System.out.println(this.getName()+"获得镜子的锁");
                }
            }
        }else {
            synchronized (mirror){
                System.out.println(this.getName()+"获得镜子的锁");
                Thread.sleep(2000);
                synchronized (lipstick){
                    System.out.println(this.getName()+"获得口红的锁");
                }
            }
        }
    }
}

解决办法

package com.beijing.xiaowen.lock;

public class DeadLock {
    public static void main(String[] args) {
        MakeUp makeUp = new MakeUp(0, "001");
        MakeUp makeUp1 = new MakeUp(1, "002");
        makeUp.start();
        makeUp1.start();
    }
}
class Lipstick{}

class Mirror{}

class MakeUp extends Thread{
    //需要的资源只有一份,用static保证
    static  Lipstick lipstick = new Lipstick();
    static Mirror mirror = new Mirror();
    int choice;
    String name;
    MakeUp(int choice,String name){
        this.choice= choice;
        this.name = name;
    }
    @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.getName()+"获得口红的锁");
                Thread.sleep(1000);
            }synchronized (mirror){
                System.out.println(this.getName()+"获得镜子的锁");
            }
        }else {
            synchronized (mirror){
                System.out.println(this.getName()+"获得镜子的锁");
                Thread.sleep(2000);
            }synchronized (lipstick){
                System.out.println(this.getName()+"获得口红的锁");
            }
        }
    }
}

lock锁(可重入锁)

package com.beijing.xiaowen.lock;

import java.util.concurrent.locks.ReentrantLock;

public class TestLock {
    public static void main(String[] args) {
        Buy buy = new Buy();
        new Thread(buy).start();
        new Thread(buy).start();
    }
}

class Buy implements Runnable{

    int num = 10;
    private final ReentrantLock reentrantLock = new ReentrantLock();
    @Override
    public void run() {
        while (true){
            try {
                reentrantLock.lock();
                if (num>0){
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(num--);
                }else {
                    break;
                }
            }finally {
                reentrantLock.unlock();
            }

        }
    }
}
 

synchronized 与 lock 对比

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

线程协作

生产者消费者模式

管程法

package com.beijing.xiaowen.scxf;

//测试:生产者消费者模型 --> 利用缓冲区解决:管程法
public class Test01 {
    public static void main(String[] args) {
        SynContainer synContainer = new SynContainer();
        new Productor(synContainer).start();
        new Consumer(synContainer).start();
    }
}
//生产者
class Productor extends Thread{
    SynContainer synContainer;
    Productor(SynContainer synContainer){
        this.synContainer = synContainer;
    }
    //生产
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            synContainer.push(new Chicken(i));
            System.out.println("生产了"+i+"只鸡");
        }

    }
}
//消费者
class Consumer extends Thread{
    SynContainer synContainer;
    Consumer(SynContainer synContainer){
        this.synContainer = synContainer;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("消费了"+synContainer.pop().id+"只鸡");
        }

    }
}

//产品
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.notifyAll();
    }
    //消费者消费产品
    public synchronized Chicken pop(){
        //判断能否消费
        if (count==0){
            //等待生产者生产。消费者等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //如果可以消费
        count--;
        Chicken chicken = chickens[count];

        //吃完了,等待生产者生产
        this.notifyAll();
        return chicken;
    }
}

信号灯法

package com.beijing.xiaowen.scxf;

//信号灯法,标志位解决
public class Test02 {
    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++) {
            this.tv.wtatch();
        }
    }
}
//产品  节目
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 wtatch(){
        if (flag){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("观看了:"+voice);
        this.notifyAll();
        this.flag = !this.flag;
    }
}

线程池

package com.beijing.xiaowen.scxf;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TestPool {
    public static void main(String[] args) {
        //创建服务,创建线程池
        ExecutorService executorService = Executors.newFixedThreadPool(10);

        //执行
        executorService.execute(new MyPool());
        executorService.execute(new MyPool());
        executorService.execute(new MyPool());
        executorService.execute(new MyPool());

        //关闭链接
        executorService.shutdown();
    }
}
class MyPool implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }
}

标签:Thread,void,System,println,new,多线程,public
From: https://www.cnblogs.com/always0708/p/16823666.html

相关文章

  • java使用线程池实现多线程
    packageA_ShangGuiGu.Thread.ThreadTest;importjava.util.concurrent.*;/***创建线程的方式四:使用线程池。*线程池的好处:*1.提高响应速度(减少了创建线程的时间)*......
  • 4.5 Kafka Consumer API之多线程并发处理
    1.Consumer一对一消费Partition(1).简介这种类型是经典模式,每一个线程单独创建一个KafkaConsumer消费一个partition,用于保证线程安全。(2).代码示例publicclassKafkaCon......
  • Java多线程(3):ThreadPool(上)
    您好,我是湘王,这是我的博客园,欢迎您来,欢迎您再来~ 开完一趟车完整的过程是启动、行驶和停车,但老司机都知道,真正费油的不是行驶,而是长时间的怠速、频繁地踩刹车等动作。因......
  • Java生产者消费者问题-多线程-线程同步-线程安全-线程通信
    packageA_ShangGuiGu.Thread.ThreadTest;/***生产者消费者问题:生产者(Producer)将商品(commodity)交给商店(Shop),消费者(Consumer)进行消费*商店里的商品数量上限为20......
  • tvm-多线程代码生成和运行
    本文链接https://www.cnblogs.com/wanger-sjtu/p/16818492.html调用链tvm搜索算子在需要多线程运行的算子,是在codegen阶段时插入TVMBackendParallelLaunch的调用。TVMB......
  • 使用多线程优化for循环请求http接口
    packagecom.test.list;importcom.alibaba.fastjson.JSON;importcom.google.common.util.concurrent.ThreadFactoryBuilder;importjava.util.*;importjava.util.concur......
  • Java多线程(2):线程关键字
    您好,我是湘王,这是我的博客园,欢迎您来,欢迎您再来~ Java中和线程相关的关键字就两:volatile和synchronized。volatile以前用得较少,以后会用得更少(后面解释)。它是一种非常轻......
  • java线程例题-类/对象/实例化/声明/多线程/同步
    packageA_ShangGuiGu.Thread.ThreadTest;importjava.util.concurrent.locks.ReentrantLock;////////////////////////////classzhanghu{//账户类,定义一个余额属性。......
  • 郁金香 -多线程创建
    #include<stdio.h>#include<Windows.h>//创建线程函数//开辟线程//BUG解决让这两个线程可以长期存在免得无法观察DWORDWINAPI线程函数1(LPVOIDarg){whil......
  • devexpress中grid控件教程 多线程异步加载数据,进度条展示
    devexpress中最强大的控件,要数它的Grid了。几乎任务数据都可以展示,但今天要用它做另一个功能。假设我们开发这样一款软件:视频编辑软件。里面有个功能,提取视频中的音频。一......