线程 简单使用

声明:此内容都是个人理解

创建线程的方式

继承 thread

实现了Runnable接口

一个普通的类继承即可变成带线程的类

通过start 方法启动线程

    

public class ticke  extends  Thread{
    private  int t = 100;
    @Override
    public void run() {
        while (t > 0) {
        System.out.println(Thread.currentThread().getName() + "购买了一个票剩余" + --t);
    }
        System.out.println("已售空");
    }

    public static void main(String[] args) {

        ticke ticke = new ticke();
 
            ticke.start();

    }
}

实现Runnable接口

Runnable的使用方法

一个普通的类实现Runnable  写下实现

启动方法 new Thread( 实现Runnable对象 , 线程名字 ).start();

和Thread的区别是实现Runnable的类可以通过New 线程的方式让不同线程去抢夺一个资源

但是当多个线程去抢夺一个资源时是不安全的,当资源被抢夺到不能够正常分配正在运行的线程的时候会发生数据重复

举个例子

假如有三个线程还剩下两个糖果,资源被读取的时候在线程内存中显示的资源还可以在抢一次或多次。结果就是当别的线程抢完糖果为0结束了他也抢到了.所以这个地方要加安全机制”锁“


public class tang  implements  Runnable {


    //现在有一百个糖果
    private  static  int  t = 100;

    @Override
    public void run() {

        while (t>0){
            System.out.println(Thread.currentThread().getName()+"拿到了一个糖果剩余"+ --t);
        }

    }


    public static void main(String[] args) {

        tang tang = new tang();
        new Thread(tang,"小明").start();
        new Thread(tang,"小红").start();
        new Thread(tang,"小黑").start();


    }


}

实现callable

线程启动方法名为call 

callable的运行方法自带返回值


public class callableTest  implements Callable<String> {

    private String str;

    public callableTest(String name){
        str=name;
    }

    @Override
    public String call() throws Exception {
        System.out.println(str);

        return "";
    }


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

        callableTest callableTest = new callableTest("第一个");
        callableTest callableTest2 = new callableTest("第二个");
        callableTest callableTest3 = new callableTest("第三个");



        // 创建执行服务:
        ExecutorService ser = Executors.newFixedThreadPool(3);
       // 提交执行:
        Future<String> result1 = ser.submit(callableTest);
        Future<String> result2 = ser.submit(callableTest2);
        Future<String> result3 = ser.submit(callableTest3);

        //获取结果:
        String r1 = result1.get();
        String r2 = result1.get();
        String r3 = result1.get();
        //关闭服务:
        ser.shutdownNow( );

    }

}

通过线程池创建可以运行的线程数量,并实例化实现Callable的类以任务的形式提交给线程池

返回任务结果可以获得线程执行的结果。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值