多线程的理解

多线程的实现方式

继承Thread类的方式

  1. 创建一个继承于Thread类的子类
  2. 重写Thread类的run() --将执行的操作声明在run()中
  3. 创建Thread类的子类的对象
  4. 通过此对象调用start():
class Thread1 extends Thread{
   //重写run()方法
   @Override
   public void run() {
       //操作
       for (int i =0;i<100;i++){
           if (i % 2 == 0 ) {
               System.out.println(i);
           }
       }
   }
}

public class ThreadTest{
   public static void main(String[] args) {
       Thread1 t1 = new Thread1();
       //启动当前线程,调用当前线程的run()方法
       t1.start();
   }
}

Thread类的相关方法

  1. start():调用当前线程的run()
  2. run():重写此方法,将要进行的操作声明在此方法中
  3. currentTread():静态方法,返回当前线程
  4. getName():获取当前线程名
  5. setName():设置当前线程名
  6. yield():释放当前cpu执行权
  7. join():在a线程中调用b的join(),a会阻塞,直到b执行完,线程a才结束阻塞状态
  8. stop():停止 过时
  9. sleep(long millis):睡眠

实现Runnable接口的方式

  1. 创建一个实现Runnable接口的类
  2. 实现类去实现Runnable中的抽象方法:run()
  3. 创建实现类对象
  4. 将此对象作为参数传递到Thread类的构造器中,创建Thread类的对象
  5. 通过Thread类的对象调用start()

实现Callable接口

  1. 创建一个类实现Callable接口
  2. 创建实现类对象
  3. 创建FutureTask封装异步任务
  4. 把FutureTask对象交给Thread对象执行
  5. 线程执行后可以通过FutureTask的get()方法获取方法call()的返回对象
public class ThreadTest {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Callable ct = new CallableTest();
        FutureTask ft = new FutureTask(ct);
        Thread t = new Thread(ft);
        t.start();
        Example e = (Example)ft.get();
        System.out.println(e);

    }
}

class CallableTest implements Callable{

    @Override
    public Example call() throws Exception {
        return new Example("例子",55);
    }
}

class Example{
    String name;
    Integer amount;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAmount() {
        return amount;
    }

    public void setAmount(Integer amount) {
        this.amount = amount;
    }

    public Example(String name, Integer amount) {
        this.name = name;
        this.amount = amount;
    }

    @Override
    public String toString() {
        return "Example{" +
                "name='" + name + '\'' +
                ", amount=" + amount +
                '}';
    }
}

使用线程池

  1. 通过Executors(异步执行框架)的类方法创建一个制定线程大小的线程池
  2. 定义一个线程对象,若要返回值则实现Callable接口
  3. 可以使用线程池对象的submit()方法获取异步任务对象
  4. 通过异步任务的get()方法获取线程中的返回值
public class ThreadTest1 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        int taskSize = 5;
        ExecutorService pool = Executors.newFixedThreadPool(taskSize);
        List<Future> list = new ArrayList<>();
        for (int i = 0;i<taskSize;i++) {
            Callable ct = new CallableTest1();
            Future future = pool.submit(ct);
            list.add(future);
        }
        pool.shutdown();
        for (Future f : list) {
            // 从Future对象上获取任务的返回值,并输出到控制台
            System.out.println(">>>" + f.get().toString());
        }
    }
}

class CallableTest1 implements Callable{

    @Override
    public Example1 call() throws Exception {
        return new Example1("例子",55);
    }
}

class Example1{
    String name;
    Integer amount;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAmount() {
        return amount;
    }

    public void setAmount(Integer amount) {
        this.amount = amount;
    }

    public Example1(String name, Integer amount) {
        this.name = name;
        this.amount = amount;
    }

    @Override
    public String toString() {
        return "Example{" +
                "name='" + name + '\'' +
                ", amount=" + amount +
                '}';
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值