Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA Tutorial
  • Data Structures
  • Algorithms
  • Array
  • Strings
  • Linked List
  • Stack
  • Queue
  • Tree
  • Graph
  • Searching
  • Sorting
  • Recursion
  • Dynamic Programming
  • Binary Tree
  • Binary Search Tree
  • Heap
  • Hashing
  • Divide & Conquer
  • Mathematical
  • Geometric
  • Bitwise
  • Greedy
  • Backtracking
  • Branch and Bound
  • Matrix
  • Pattern Searching
  • Randomized
Open In App
Next Article:
MultiThreading in Android with Examples
Next article icon

MultiThreading in Android with Examples

Last Updated : 01 Aug, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report

Working on multiple tasks at the same time is Multitasking. In the same way, multiple threads running at the same time in a machine is called Multi-Threading. Technically, a thread is a unit of a process. Multiple such threads combine to form a process. This means when a process is broken, the equivalent number of threads are available. 
For example, Autocorrect is the process where the software looks for the mistakes in the current word being typed. Endlessly checking for the mistake and providing suggestions at the same time is an example of a Multi-Threaded process. 

Sample Android App:

Let's try to visualize Multi-Threading with the help of an Android App. In the below example, 3 Threads start at the same time on a button click and work concurrently. 

Approach: 
Step 1: Add the below code in activity_main.xml. Here we add three TextViews and a button.
 

XML
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout      xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:app="http://schemas.android.com/apk/res-auto"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent"     tools:context=".MainActivity">      <TextView         android:id="@+id/tv1"         android:layout_width="75sp"         android:layout_height="75sp"         android:background="@color/colorPrimary"         android:textColor="@color/colorAccent"         android:gravity="center"         android:textSize="10sp"         android:layout_centerVertical="true"         android:layout_toLeftOf="@id/tv2"         />      <TextView         android:id="@+id/tv2"         android:layout_width="75sp"         android:layout_height="75sp"         android:background="@color/colorPrimary"         android:textColor="@color/colorAccent"         android:gravity="center"         android:textSize="10sp"         android:layout_centerInParent="true"         />      <TextView         android:id="@+id/tv3"         android:layout_width="75sp"         android:layout_height="75sp"         android:background="@color/colorPrimary"         android:textColor="@color/colorAccent"         android:gravity="center"         android:textSize="10sp"         android:layout_centerVertical="true"         android:layout_toRightOf="@id/tv2"         />      <Button         android:id="@+id/btnStart"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:text="Start"         android:layout_centerHorizontal="true"         android:layout_below="@id/tv2"         />  </RelativeLayout> 

Step 2: Add the below code in MainActivity. Here, three threads are made, each thread keeps updating the respective TextView every second (declared in the code) when the button is clicked. These Threads keep running until the button is clicked again (i.e."Stop"). 
 

Java
class MainActivity : AppCompatActivity() {     @SuppressLint("SetTextI18n")     override fun onCreate(savedInstanceState: Bundle?)     {         super.onCreate(savedInstanceState)             setContentView(R.layout.activity_main)              // Assigning Layout elements             val tv1             = findViewById<TextView>(R.id.tv1)                 val tv2             = findViewById<TextView>(R.id.tv2)                 val tv3             = findViewById<TextView>(R.id.tv3)                 val btn             = findViewById<Button>(R.id.btnStart)              // Boolean for Button (initially False)             var boolbtn             = false               // Button onClick action               btn.setOnClickListener         {             // Button (True)             boolbtn = !boolbtn                       // Case where Button is False                       if (!boolbtn)             {                 tv1.text = "Stopped1"                 tv2.text = "Stopped2"                 tv3.text = "Stopped3"                 btn.text = "Start"             }             // Case where Threads are running             else             {                 // Setting the button text as "Stop"                 btn.text = "Stop"                             // Thread 1                            Thread(Runnable {                                 // Runs only when Button is True                                while (boolbtn) {                                     runOnUiThread                                    {                                        tv1.text = "Started1"                                    }                                    Thread.sleep(1000)                                        runOnUiThread                                    {                                        tv1.text = "Activity1"                                    }                                    Thread.sleep(1000)                                }                            }).start()                             // Thread 2                            Thread(Runnable {                                   // Runs only when Button is                                  // True                                  while (boolbtn) {                                      runOnUiThread                                      {                                          tv2.text = "Started2"                                      }                                      Thread.sleep(1000)                                          runOnUiThread                                      {                                          tv2.text = "Activity2"                                      }                                      Thread.sleep(1000)                                  }                              }).start()                             // Thread 3                            Thread(Runnable {                                     // Runs only when Button is                                    // True                                    while (boolbtn) {                                        runOnUiThread                                        {                                            tv3.text = "Started3"                                        }                                        Thread.sleep(1000)                                            runOnUiThread                                        {                                            tv3.text = "Activity3"                                        }                                        Thread.sleep(1000)                                    }                                })                                .start()             }         }     } } 

Output:
 


Multi-Threading concept applies to a large number of day to day applications on various machines. However, there are drawbacks to the same. At the beginner level, one can only think of the load on the machine or increased complexity. But at a greater level, multiple scenarios such as complex testing, unpredictable results, deadlock, starvation, etc are expected.
 


Next Article
MultiThreading in Android with Examples

A

aashaypawar
Improve
Article Tags :
  • Java
  • Competitive Programming
  • Operating Systems
  • Aptitude
  • Computer Science Quizzes
  • Java Quiz
  • Kotlin
  • Android
  • DSA
Practice Tags :
  • Java

Similar Reads

    What are Threads in Android with Example?
    In Android, a thread is a separate path of execution. By default, your app runs on a single main thread (UI thread). All user interactions, UI updates, and view rendering happen on this main thread. If you perform long-running operations (like network requests, database access, or heavy computation)
    4 min read
    Synchronization in Android with Example
    In Android, synchronization refers to the process of ensuring that data stored in multiple locations is the same and up-to-date. This can be achieved through various methods such as using the built-in Android synchronization adapters, or by manually implementing synchronization using the Android Syn
    5 min read
    Intent Service in Android with Example
    An IntentService is a subclass of Service in Android that is used to handle asynchronous requests (expressed as "Intents") on demand. It runs in the background and stops itself once it has processed all the intents that were sent to it. An IntentService in Java and Kotlin: Kotlin class MyIntentServi
    5 min read
    Services in Android with Example
    Services in Android are a special component that facilitates an application to run in the background in order to perform long-running operation tasks. The prime aim of a service is to ensure that the application remains active in the background so that the user can operate multiple applications at t
    10 min read
    Internal Storage in Android with Example
    The aim of this article is to show users how to use internal storage. In this article will be creating an application that can write data to a file and store it in internal storage and read data from the file and display it on the main activity using TextView. Saving and loading data on the internal
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences