Java线程操作

Java操作线程Demo

背景

自己设计业务场景,根据Java代码去完成并发操作,利用信号量协调线程的运行情况,并利用线程和线程池去完成对应操作。

直接创建线程执行

线程之间信号量定义Temp

整个线程运行过程中,通过Temp去定义整体并发任务的执行情况

/**
 * @author jiajie
 * 线程总数执行情况
 */
public class Temp {
    /**
     * 任务总数
     */
    private int sum;
    /**
     * 当前执行完任务数量
     */
    private volatile int current;
    /**
     * 当所有任务执行完时,b变为true
     */
    private volatile boolean b;
    /**
     * 锁
     */
    private Lock lock = new ReentrantLock();

    public void add() {
        try {
            lock.lock();
            current++;
            if (current == sum) {
                b = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }

    public int getSum() {
        return sum;
    }

    public Temp(int sum) {
        this.sum = sum;
    }

    public boolean isB() {
        return b;
    }
}

主方法

/**
 * @author jiajie
 * 直接将任务创建线程调用
 */
public class ThreadDemo01 {
    public static void main(String[] args) throws InterruptedException {
        // x是任务数量,也是线程数量
        int x = 4;
        Temp temp = new Temp(x);
        Thread.currentThread().setName("主线程");
        for (int y = 0; y < x; y++) {
            Thread my1 = new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int i = 1; i <= 50; i++) {
                        System.out.println(Thread.currentThread().getName() + "执行了:" + i);
                    }
                    temp.add();
                    if (temp.isB()) {
                        synchronized (this) {
                            notify();
                        }
                    }
                }
            });
            my1.setName(y + "");
            my1.start();
        }

        while (!temp.isB()) {
            System.out.println("主线程自旋判断子线程执行完毕");
            Thread.sleep(10);
        }

        for (int i = 1; i <= 50; i++) {
            System.out.println(Thread.currentThread().getName() + "执行了:" + i);
        }
    }
}

用线程池去完成任务


/**
 * @author jiajie
 * 使用线程池方法
 */
public class ThreadDemo02 {
    public static void main(String[] args) throws InterruptedException {
        // x是任务数量
        int sum = 11;
        Thread.currentThread().setName("主线程");
        // 任务执行详细
        Temp temp = new Temp(sum);
        ExecutorService pool = execute(temp);
        // 如果子线程执行完毕,主线程就不再进行自旋
        while (!temp.isB()) {
            System.out.println("主线程自旋判断子线程执行完毕");
            Thread.sleep(10);
        }
        // 主线程其他后续任务
        for (int i = 1; i <= 50; i++) {
            System.out.println(Thread.currentThread().getName() + "执行了:" + i);
        }
        System.out.println("线程结束");
        // 终止线程池
        pool.shutdown();
    }

    public static ExecutorService execute(Temp temp) {
        //1.创建线程池
        ExecutorService pool = new ThreadPoolExecutor(
                3,
                10,
                4,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(20),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy()
        );

        for (int y = 0; y < temp.getSum(); y++) {
            //2. 给任务线程池处理
            pool.execute(new Runnable() {
                @Override
                public void run() {
                    for (int i = 1; i <= 50; i++) {
                        System.out.println(Thread.currentThread().getName() + "执行了:" + i);
                    }
                    temp.add();
                    if (temp.isB()) {
                        synchronized (this) {
                            notify();
                        }
                    }
                }
            });
        }
        return pool;
    }
}

多任务并发操作

创建子线程的守护线程,不停的查看煮开水的情况,还有客户催菜的情况
在这里插入图片描述

子线程的守护线程类

/**
 * @author jiajie
 * 充当子线程的守护线程
 */
public class RunnableDemo implements Runnable{
    private boolean b = true;
    @Override
    public void run() {
        // 守护线程
        while (b) {
            System.out.println("查看水煮的情况");
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    
    public void setB(boolean b) {
        this.b = b;
    }
}

主方法

/**
 * @author jiajie
 */
public class ThreadDemo03 {
    public static void main(String[] args) throws InterruptedException {

        Thread.currentThread().setName("主线程");
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                // 守护线程
                while (true) {
                    System.out.println("客户查看菜做的情况");
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        thread.setDaemon(true);
        thread.start();
        // 任务执行详细
        Temp temp = new Temp(3);
        //1.创建线程池
        ExecutorService pool = new ThreadPoolExecutor(
                3,
                10,
                4,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(20),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy()
        );
        // 给任务线程池处理切菜
        pool.execute(new Runnable() {
            @Override
            public void run() {
                // 执行对应线程任务
                System.out.println("切菜");
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                temp.add();
            }
        });
        // 给任务线程池处理煮开水
        pool.execute(new Runnable() {
            @Override
            public void run() {
                // 执行对应线程任务
                System.out.println("煮开水");
                // 子线程的守护线程
                RunnableDemo r = new RunnableDemo();
                Thread thread = new Thread(r);
                thread.start();
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                r.setB(false);
                System.out.println("开水煮好了!");
                temp.add();
            }
        });
        // 给任务线程池处理洗碗
        pool.execute(new Runnable() {
            @Override
            public void run() {
                // 执行对应线程任务
                System.out.println("洗碗");
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                temp.add();
            }
        });

        // 如果子线程执行完毕,主线程就不再进行自旋
        while (!temp.isB()) {
            System.out.println("主线程自旋判断子线程执行中");
            Thread.sleep(100);
        }
        System.out.println("炒菜");
        Thread.sleep(300);
        System.out.println("炒菜结束,上菜");
        // 终止线程池
        pool.shutdown();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值