当前位置: 移动技术网 > IT编程>开发语言>Java > java 实现多线程的方法总结

java 实现多线程的方法总结

2019年07月22日  | 移动技术网IT编程  | 我要评论

芦山县,欧美男体博客,三支一扶考试

java 实现多线程的三种方法

在java中,有三种方法可以实现多线程。第一种方法:继承thread类,重写run函数。第二种方法:实现runnable接口,重写run函数。第三种方法:实现callable接口,重写call函数。本文章将通过实例讲解这三种方法如何实现多线程。需要的可以参考一下。

 (1)继承thread类,重写run函数。

class xx extends thread{
     public void run(){
      thread.sleep(1000)  //线程休眠1000毫秒,sleep使线程进入block状态,并释放资源
    }}

开启线程:

对象.start()    //启动线程,run函数运行

(2)实现runnable接口,代码如下

class mythread implements runnable {
  
  private string name;
  
  public mythread(string name) {
    super();
    this.name = name;
  }
  
  @override
  public void run() {
    for(int i = 0 ; i < 200; i++) {
      system.out.println("thread"+name+"--->"+i);
    }  
  }
}

public class threaddemo {

  public static void main(string[] args) {
    mythread a = new mythread("a");
    mythread b = new mythread("b");
    mythread c = new mythread("c");
    new thread(a).start();
    new thread(b).start();
    new thread(c).start();
  }
}

(3)实现callable接口,重写call函数

callable是类似于runnable的接口,实现callable接口的类和实现runnable的类都是可被其它线程执行的任务。

callable和runnable有几点不同:

  1. callable规定的方法是call(),而runnable规定的方法是run().
  2. callable的任务执行后可返回值,而runnable的任务是不能返回值的
  3. call()方法可抛出异常,而run()方法是不能抛出异常的。
  4. 运行callable任务可拿到一个future对象,future表示异步计算的结果。它提供了检查计算是否完成的方法,以等待计算的完成,并检索计算的结果.通过future对象可了解任务执行情况,可取消任务的执行,还可获取任务执行的结果

java  callable 代码示例:

class taskwithresult implements callable<string> {
 private int id;

 public taskwithresult(int id) {
 this.id = id;
 }

 @override
 public string call() throws exception {
 return "result of taskwithresult " + id;
 }
}

public class callabletest {
 public static void main(string[] args) throws interruptedexception,
  executionexception {
 executorservice exec = executors.newcachedthreadpool();
 arraylist<future<string>> results = new arraylist<future<string>>(); //future 相当于是用来存放executor执行的结果的一种容器
 for (int i = 0; i < 10; i++) {
  results.add(exec.submit(new taskwithresult(i)));
 }
 for (future<string> fs : results) {
  if (fs.isdone()) {
  system.out.println(fs.get());
  } else {
  system.out.println("future result is not yet complete");
  }
 }
 exec.shutdown();
 }
}
 

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网