Home > Java > javaTutorial > Implementation method of multi-threading based on java learning

Implementation method of multi-threading based on java learning

高洛峰
Release: 2017-03-19 11:23:52
Original
1684 people have browsed it

这篇文章介绍基于java学习中多线程的实现方法

1 继承Thread类

继承Thread类的方法尽管被我列为一种多线程实现方式,但Thread本质上也是实现了Runnable接口的一个实例,它代表一个线程的实例,并且,启动线程的唯一方法就是通过Thread类的start()实例方法。start()方法是一个native方法,它将启动一个新线程,并执行run()方法。这种方式实现多线程很简单,通过自己的类直接extend Thread,并复写run()方法,就可以启动新线程并执行自己定义的run()方法。

public class MyThread extends Thread {  
  public void run() {  
   System.out.println("MyThread.run()");  
  }  
} 
 //启动线程
MyThread myThread1 = new MyThread();  
MyThread myThread2 = new MyThread();  
myThread1.start();  
myThread2.start();
Copy after login

2 实现Runnable接口

如果一个类继承另一个类,就无法继承Thread类(java中不支持多继承),这样就要实现Runnable接口,在实现类中重写run()方法,在main方法中实现多线程:实例化一个实现类对象,并初始化Thread类的对象,把实现类传入到Thread的对象里。事实上,当传入一个Runnable target参数给Thread后,Thread的run()方法就会调用target.run()。

//实现Runnable接口
public class MyThread extends OtherClass implements Runnable {  
  public void run() {  
   System.out.println("MyThread.run()");  
  }  
}  
//复写run()方法
public void run() {  
  if (target != null) {  
   target.run();  
  }  
} 
//实例化对象
MyThread myThread = new MyThread();  
Thread thread = new Thread(myThread);  
thread.start();
Copy after login

3 使用ExecutorService、Callable、Future实现有返回结果的多线程

该部分内容还未学到占时不作记录,以后补充


The above is the detailed content of Implementation method of multi-threading based on java learning. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template