{"id":16104914,"url":"https://github.com/dbc2201/multithreading","last_synced_at":"2025-03-18T08:31:31.280Z","repository":{"id":133011808,"uuid":"306215912","full_name":"dbc2201/MultiThreading","owner":"dbc2201","description":"Repository for classroom codes and reading material for the concept of Multi-Threading in Java","archived":false,"fork":false,"pushed_at":"2020-10-29T08:03:30.000Z","size":73,"stargazers_count":6,"open_issues_count":0,"forks_count":28,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-02-28T08:20:08.037Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Java","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/dbc2201.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-10-22T03:50:14.000Z","updated_at":"2023-01-16T18:47:10.000Z","dependencies_parsed_at":null,"dependency_job_id":"25d1af52-edfb-403e-a92c-5f611baa0182","html_url":"https://github.com/dbc2201/MultiThreading","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dbc2201%2FMultiThreading","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dbc2201%2FMultiThreading/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dbc2201%2FMultiThreading/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dbc2201%2FMultiThreading/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/dbc2201","download_url":"https://codeload.github.com/dbc2201/MultiThreading/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243910750,"owners_count":20367545,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-10-09T19:06:58.919Z","updated_at":"2025-03-18T08:31:31.275Z","avatar_url":"https://github.com/dbc2201.png","language":"Java","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Multi-Threading in Java\n\n- A `multithreaded` program in Java contains two or more parts that can run\n [`concurrently`](https://www.google.com/search?q=concurrently+meaning), each part of the program is called a \n `thread`.\n- Each `thread` defines a separate path of execution, hence we can say that `multithreading` is a \nspecial case of `multitasking`.\n\n## Type of Multitasking\n1. Process-based\n2. Thread-based\n\n- A `process` is essentially a program that is executing, hence, `process-based` multitasking is the feature that allows\na computer to run (or execute) two or more program concurrently.\nFor example, `Process-based` multitasking allows us to run the Java IDE, Zoom, Google Chrome, WhatsApp etc at the same\ntime on our computer. Here, a program is the smallest unit of code that can be dispatched by the scheduler.\n\n- In a `thread-based` multitasking environment, a `thread` is the smalled unit of code that can be dispatched by the\nscheduler. This means that a single program can execute two or more tasks\n[simultaneously](https://www.google.com/search?q=simultaneously+meaning).\nFor example, we can still edit the code in our IDE when the compiler is compiling it\nor the JVM is executing it, as long as these two tasks are being performed on two different threads.\n\nThus, we can say that,\n- The `process-based` multitasking handles the \"big-picture\", and\n- The `thread-based` multitasking handles the \"fine-details\".\n\n**Multitasking threads require less resources than multitasking processes.**\n\n## The Java Thread Model\n\nThe `multi-threading` capabilities of Java are built-in.\n\nStates of a thread in Java\n1. Running (currently executing)\n2. Suspended (paused, after running)\n3. Resumed (starting after paused)\n4. Blocked (not running, and waiting for a resource)\n5. Ready (waiting to run)\n6. Terminated (halted OR stopped)\n\n**Thread Priorities**\nThe Java compiler will assign a `priority` to a thread.\nThis priority will tell us that how which thread should be treated with respect to others.\nBasically, these are some integer values.\nBut a higher priority of a thread can not guarantee that a thread will perform its task\nfast or slow, if it is the only thread running.\nPriority of a thread can only be observed properly once there are two or more threads\nrunning concurrently in a program space.\nIt is basically used to decide that when to switch from one running thread to the next\n(context switch).\nThere are basic two rules for context switching\n1. `A thread can voluntarily relinquish(to lose) control`:\nThis happens when explicitly yielding, sleeping, or when the thread is blocked.\nIn this, all other threads are examines, and the thread with the highest priority will be \nmarked as ready to run.\n2. `A thread can be preempted by a higher-priority thread`:\nIn this, a thread with a low-priority does not yield the processor, but when it is \npreempted by a higher-priority processor, it will yield.\n \n# The `Thread` class and the `Runnable` Interface.\n\nJava's multithreading system is built upon the `Thread` class, and its companion\ninterface, the `Runnable` interface. \n\n## The `Main` Thread\n\n- Whenever a Java program executes, one thread starts running immediately,\nthis is called the `main` thread of the program.\n\n- It is important for two main reasons.\n1. It is the thread from which all the other threads will be created.\n2. It must be the last thread to finish execution because it performs various shutdown \nactions.\n\n## Creating a `Thread`\n1. By implementing the `Runnable` interface.\n2. By extending the `Thread` class.\n\n### 1. By implementing the `Runnable` Interface\n- Create a _definition_ class.\n```java\nclass ThreadWithRunnableInterface {\n}\n```\n- Implement the `Runnable` interface in the class.\n```java\nclass ThreadWithRunnableInterface implements Runnable {\n}\n```\n- Implement the `run()` method from the Runnable Interface; remember, \nthe `java.lang.Runnable` interface is a functional interface.\n```java\nclass ThreadWithRunnable implements Runnable {\n    @Override\n    public void run() {}\n}\n```\n- Create a _field_ of the `Thread` type for the class; make it\n`private` and `final`.\n```java\nclass ThreadWithRunnable implements Runnable {\n    private final Thread thread;\n    @Override\n    public void run() {}\n}\n```\n- Create a `public` constructor for the class.\n```java\nclass ThreadWithRunnable implements Runnable {\n    private final Thread thread;\n\n    public ThreadWithRunnable() {}    \n\n    @Override\n    public void run() {}\n}\n```\n- Initialize the _`thread` field_ inside the constructor.\n\u003e The String parameter inside the constructor of the Thread class\n\u003e is the name of the thread.\n```java\nclass ThreadWithRunnable implements Runnable {\n    private final Thread thread;\n\n    public ThreadWithRunnable() {\n        thread = new Thread(this, \"Thread Name\");\n    }    \n\n    @Override\n    public void run() {}\n}\n``` \n- **Optional**: If you would like to expose the thread field outside this class,\nyou may do so by defining a _`getter`_ method for the field.\n```java\nclass ThreadWithRunnable implements Runnable {\n    private final Thread thread;\n\n    public ThreadWithRunnable() {\n        thread = new Thread(this, \"Thread Name\");\n    }    \n\n    public Thread getThread() {\n        return thread;\n    }\n\n    @Override\n    public void run() {}\n}\n``` \n**AND THAT'S ABOUT IT!!**\nNow, you can create an object of this class and call the `start()` method to \nexecute this thread.\n```java\nclass ThreadRunner {\n    public static void main(String[] args){\n        ThreadWithRunnable thread1 = new ThreadWithRunnable();\n        thread1.start();\n    }\n}\n```\n**EXTRA**: You can specify your thread to sleep(pause) for some time using the\n_static_ `sleep()` method of the `java.lang.Thread` class.  \nJust remember that this method might cause an `InterruptedException`,\nsince this is an unhandled exception, we will wrap the `sleep()` method inside\na `try/catch` block.\n```java\nclass ThreadWithRunnable implements Runnable {\n    private final Thread thread;\n\n    public ThreadWithRunnable() {\n        thread = new Thread(this, \"Thread Name\");\n    }    \n\n    @Override\n    public void run() {\n        try {\n            Thread.sleep(500L);\n        } catch (InterruptedException e) {\n            System.err.println(e.getMessage());\n        }\n    }\n}\n``` \n---\n### 2. By extending the `Thread` class.\n\n- Create a definition class.\n```java\nclass ThreadWithThreadClass {\n}\n```\n\n- Extend the `java.lang.Thread` class; since the `Thread` class is present in the \n`java.lang` package, we do not need to import it specifically.\n```java\nclass ThreadWithThreadClass extends Thread {\n}\n```\n\n- Create a constructor and call the constructor of the parent class (The `Thread` class) \nvia `super()`. In the call to the `super()` constructor, pass the name of the thread.\n```java\nclass ThreadWithThreadClass extends Thread {\n\n    public ThreadWithThreadClass() {\n        super(\"SimpleThread\");\n    }\n\n}\n```\n\n- **EXTRA** If you want, you can overload the constructor also like this\n```java\nclass ThreadWithThreadClass extends Thread {\n\n    public ThreadWithThreadClass() {\n        super(\"SimpleThread\");\n    }\n\n    public ThreadWithThreadClass(String threadName){\n        super(threadName);\n    }\n\n}\n```\n- Next, we need to override the `run()` method from the `Thread` class.\n```java\nclass ThreadWithThreadClass extends Thread {\n\n    public ThreadWithThreadClass() {\n        super(\"SimpleThread\");\n    }\n\n    @Override\n    public void run() {\n        // Specify the task for your thread here!\n    }   \n\n}\n```\n**AND THAT'S ABOUT IT!!**\nNow, you can create an object of this class and call the `run()` method to \nexecute this thread.\n```java\nclass ThreadRunner {\n    public static void main(String[] args){\n        ThreadWithThreadClass thread1 = new ThreadWithThreadClass(\"PUBG\");\n        thread1.run();\n    }\n}\n```","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdbc2201%2Fmultithreading","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdbc2201%2Fmultithreading","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdbc2201%2Fmultithreading/lists"}