java case12 多线程 线程安全 线程池

线程写法1  无法返回结果

package test3;//无法返回结果

public class Demo3Thread {
    public static void main(String[] args) {
        Runnable target = new Runnable() {
            /**
             * 匿名内部类
             */
            @Override
            public void run() {
                for (int i = 0; i < 5; i++) {
                    System.out.println("子线程1:" + i);
                }
            }
        };

        Thread t1 = new Thread(target);
        t1.start();


        new Thread(() -> {
                for (int i = 0; i < 5; i++) {
                    System.out.println("子线程2:"+i);
                }
        }).start();


        Thread t = new mythread();
        t.start();

        for (int i = 0; i < 5; i++) {
            System.out.println("主线程:"+i);

        }
    }
}

class mythread extends Thread{
    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println("子线程:"+i);
        }
    }
}


线程写法二   可以返回结果

package test3;

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

/**
 * callabel
 */

public class Demo4Thread {
    public static void main(String[] args) {
        Callable<String> call= new mycallabel(100);
        FutureTask<String> f1 = new  FutureTask<>(call);
        Thread t2 = new Thread(f1);
        t2.start();
        try {
            String rs1 = f1.get();
            System.out.println(rs1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class mycallabel implements Callable<String>{
    private int n;

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

    @Override
    public String call() throws Exception {
        int sum = 0;
        for (int i = 0; i < n; i++) {
            sum += i;
        }
        return "子线程的结果为:"+sum;
    }
}

线程安全问题---------》上锁

package Case;

/**
 * 多线程安全 atm取钱
 */

public class Case6 {
    public static void main(String[] args) {
        atm acc = new atm("icbc",10000);
        new drawmoney(acc,"ming").start();
        new drawmoney(acc,"hong").start();

    }

}
package Case;

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

public class atm {
    private String cardid;
    private double money;

    //2
    private final Lock lock = new ReentrantLock();


    public atm() {
    }

    public atm(String cardid, double money) {
        this.cardid = cardid;
        this.money = money;
    }

    public String getCardid() {
        return cardid;
    }

    public void setCardid(String cardid) {
        this.cardid = cardid;
    }

    public double getMoney() {
        return money;
    }

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

    public void drawmoney(double money) {
//        synchronized (this) {
//            String name =Thread.currentThread().getName();
//            if(this.money>=money){
//                System.out.println(name+"取钱成功,吐出"+money);
//                this.money -= money;
//                System.out.println("剩余"+this.money);
//            }else {
//                System.out.println(name+"余额不足");
//            }
        //2
        String name = Thread.currentThread().getName();
        lock.lock();

        try {
            if (this.money >= money) {
                System.out.println(name + "取钱成功,吐出" + money);
                this.money -= money;
                System.out.println("剩余" + this.money);
            } else {
                System.out.println(name + "余额不足");
            }
        } finally {
            lock.unlock();
        }

    }
}

运行结果

线程池

 

package test3;

import java.util.concurrent.*;

public class Demo5 {
    public static void main(String[] args) {
        /**
         * public ThreadPoolExecutor(int corePoolSize,
         *                               int maximumPoolSize,
         *                               long keepAliveTime,
         *                               TimeUnit unit,
         *                               BlockingQueue<Runnable> workQueue,
         *                               ThreadFactory threadFactory,
         *                               RejectedExecutionHandler handler)
         */
        ExecutorService pool = new ThreadPoolExecutor(3,5,6, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(5),Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());
        Runnable t =new mYRUNABLE();
        pool.execute(t);
        pool.execute(t);
        pool.execute(t);
        pool.execute(t);
        pool.execute(t);
        pool.execute(t);

    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值