Home Java javaTutorial There are two ways to create new threads in Android: implements Runnable and extends Thread

There are two ways to create new threads in Android: implements Runnable and extends Thread

Sep 17, 2018 am 09:22 AM

The content of this article is about two ways to create new threads in Android: implements Runnable and extends Thread. It has certain reference value and friends in need can refer to it. I hope it helps you.

  具体分析
      最近在学习Android中的Handler消息传递机制时,创建新线程有两种方式:
      一种是实现Runnable接口(implements Runnable)而另一种则是继承Thread类(extends Thread)。
      而这两种方式有什么异同呢?
      带着这个疑问,Google了一些资料出来,本着分享给大家同时也方便自己查阅复习,写一篇文章来记录它。
       首先看看这两种方式都是怎样的?
Copy after login
1 public class ThreadA implements Runnable { 

 2     public void run() { 

 3         //Code 

 4     } 

 5 } 

 6 //调用 “new Thread(threadA).start()” 来开启线程 

 7  

 8 public class ThreadB extends Thread { 

 9     public ThreadB() { 
10         super(“ThreadB”); 
11     } 
12     public void run() { 
13         //Code 
14     } 
15 } 
16 //调用 “threadB.start()” 来开启线程
Copy after login

The two methods achieve the same work but there are still some differences between them.

         它们之间的不同是:

          1.我们都知道,Java是单继承机制,不允许同时继承多个类。
          因此,当你继承Thread类(extends Thread)后,你就不能再继承其他类了。
          而你实现Runnable接口就不一样了,你可以继承其他类了。

          2.当你继承Thread类时,你的每一个Thread对象创造不同的对象然后关联它们。
Copy after login

Inheriting the Runnable interface is different, multiple threads share an object.

          用一个例子来帮助我们理解:
Copy after login
1 class ImplementsRunnable implements Runnable { 

 2 

 3      private int counter = 0; 

 4 

 5     public void run() { 

 6     counter++; 

 7     System.out.println(“ImplementsRunnable : Counter : ” + counter); 

 8     } 

 9  } 
10 
11  class ExtendsThread extends Thread { 
12 
13    private int counter = 0; 
14 
15  public void run() { 
16    counter++; 
17    System.out.println(“ExtendsThread : Counter : ” + counter); 
18  } 
19  } 
20 
21  public class ThreadVsRunnable { 
22 
23  public static void main(String args[]) throws Exception { 
24  //多线程共享一个对象 
25    ImplementsRunnable rc = new ImplementsRunnable(); 
26    Thread t1 = new Thread(rc); 
27    t1.start(); 
28    Thread.sleep(1000); // 在开启下个线程前先等待1秒 
29    Thread t2 = new Thread(rc); 
30    t2.start(); 
31    Thread.sleep(1000); // 在开启下个线程前先等待1秒 
32    Thread t3 = new Thread(rc); 
33    t3.start(); 
34 
35  //为每一个线程创造新的实例 
36    ExtendsThread tc1 = new ExtendsThread(); 
37    tc1.start(); 
38    Thread.sleep(1000); // 在开启下个线程前先等待1秒 
39    ExtendsThread tc2 = new ExtendsThread(); 
40    tc2.start(); 
41    Thread.sleep(1000); // 在开启下个线程前先等待1秒 
42    ExtendsThread tc3 = new ExtendsThread(); 
43    tc3.start(); 
44  } 
45  }
Copy after login

Running results:

      从运行的结果,我们可以看出。实现Runnable接口,只创建了一个类的实例,而且被多个线程共享了。
      因此Counter递增。而继承Thread类,你必须为每一个线程创建不同的实例。
      因此每个类的实例分配了不同的内存空间,每一个有不同的Counter,它们的值相同。
      这意味着没有增加因为没有一个对象的引用是相同的。
       那什么时候用Runnable接口呢?
        当你想要在一组线程中访问相同的资源时,使用Runnable接口。
        在这种情况下要避免使用Thread类,因为多对象的创建会占用更多的内存,会导致大的性能花费。
Copy after login

The above is the detailed content of There are two ways to create new threads in Android: implements Runnable and extends Thread. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

See all articles