Difference between revisions of "JAVA: Multithreading"

From OnnoWiki
Jump to navigation Jump to search
(Created page with "Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilization of CPU. Each part of such program is called a threa...")
 
 
(4 intermediate revisions by the same user not shown)
Line 1: Line 1:
Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilization of CPU. Each part of such program is called a thread. So, threads are light-weight processes within a process.
+
Multithreading adalah fitur Java yang memungkinkan eksekusi bersamaan dari dua atau lebih bagian program untuk pemanfaatan CPU secara maksimal. Setiap bagian dari program tersebut disebut thread. Jadi, thread adalah proses ringan dalam suatu proses.
  
Threads can be created by using two mechanisms :  
+
Thread dapat dibuat dengan menggunakan dua mekanisme:
 +
* Memperluas Thread class
 +
* Implementing Runnable Interface
  
Extending the Thread class
 
Implementing the Runnable Interface
 
Thread creation by extending the Thread class
 
We create a class that extends the java.lang.Thread class. This class overrides the run() method available in the Thread class. A thread begins its life inside run() method. We create an object of our new class and call start() method to start the execution of a thread. Start() invokes the run() method on the Thread object.
 
  
 +
==Create Thread dengan cara meng-extend Thread class==
 +
 +
Kita membuat Class yang memperluas Class java.lang.Thread. Class ini override method run() yang tersedia di Class Thread. Sebuah Thread memulai kehidupannya di dalam method run(). Kita membuat object Class baru dan memanggil metode start() untuk memulai eksekusi Thread. Start() memanggil metode run() pada object Thread.
 +
 +
// Java code for thread creation by extending
 +
// the Thread class
 +
class MultithreadingDemo extends Thread {
 +
    public void run()
 +
    {
 +
        try {
 +
            // Displaying the thread that is running
 +
            System.out.println(
 +
                "Thread " + Thread.currentThread().getId()
 +
                + " is running");
 +
        }
 +
        catch (Exception e) {
 +
            // Throwing an exception
 +
            System.out.println("Exception is caught");
 +
        }
 +
    }
 +
}
 +
 
 +
// Main Class
 +
public class Multithread {
 +
    public static void main(String[] args)
 +
    {
 +
        int n = 8; // Number of threads
 +
        for (int i = 0; i < n; i++) {
 +
            MultithreadingDemo object
 +
                = new MultithreadingDemo();
 +
            object.start();
 +
        }
 +
    }
 +
}
  
// Java code for thread creation by extending
 
// the Thread class
 
class MultithreadingDemo extends Thread {
 
    public void run()
 
    {
 
        try {
 
            // Displaying the thread that is running
 
            System.out.println(
 
                "Thread " + Thread.currentThread().getId()
 
                + " is running");
 
        }
 
        catch (Exception e) {
 
            // Throwing an exception
 
            System.out.println("Exception is caught");
 
        }
 
    }
 
}
 
 
// Main Class
 
public class Multithread {
 
    public static void main(String[] args)
 
    {
 
        int n = 8; // Number of threads
 
        for (int i = 0; i < n; i++) {
 
            MultithreadingDemo object
 
                = new MultithreadingDemo();
 
            object.start();
 
        }
 
    }
 
}
 
 
Output
 
Output
Thread 15 is running
+
Thread 15 is running
Thread 14 is running
+
Thread 14 is running
Thread 16 is running
+
Thread 16 is running
Thread 12 is running
+
Thread 12 is running
Thread 11 is running
+
Thread 11 is running
Thread 13 is running
+
Thread 13 is running
Thread 18 is running
+
Thread 18 is running
Thread 17 is running
+
Thread 17 is running
Thread creation by implementing the Runnable Interface
 
We create a new class which implements java.lang.Runnable interface and override run() method. Then we instantiate a Thread object and call start() method on this object.
 
 
  
 +
==Creat Thread dengan cara meng-implementasi Runnable Interface==
  
// Java code for thread creation by implementing
+
Kita membuat Class baru yang mengimplementasikan java.lang.Runnable interface dan override method run(). Kemudian kita membuat instance objek Thread dan memanggil method start() pada object ini.
// the Runnable Interface
+
class MultithreadingDemo implements Runnable {
+
// Java code for thread creation by implementing
    public void run()
+
// the Runnable Interface
    {
+
class MultithreadingDemo implements Runnable {
        try {
+
    public void run()
            // Displaying the thread that is running
+
    {
            System.out.println(
+
        try {
                "Thread " + Thread.currentThread().getId()
+
            // Displaying the thread that is running
                + " is running");
+
            System.out.println(
        }
+
                "Thread " + Thread.currentThread().getId()
        catch (Exception e) {
+
                + " is running");
            // Throwing an exception
+
        }
            System.out.println("Exception is caught");
+
        catch (Exception e) {
        }
+
            // Throwing an exception
    }
+
            System.out.println("Exception is caught");
}
+
        }
 +
    }
 +
}
 
   
 
   
// Main Class
+
// Main Class
class Multithread {
+
class Multithread {
    public static void main(String[] args)
+
    public static void main(String[] args)
    {
+
    {
        int n = 8; // Number of threads
+
        int n = 8; // Number of threads
        for (int i = 0; i < n; i++) {
+
        for (int i = 0; i < n; i++) {
            Thread object
+
            Thread object
                = new Thread(new MultithreadingDemo());
+
                = new Thread(new MultithreadingDemo());
            object.start();
+
            object.start();
        }
+
        }
    }
+
    }
}
+
}
 +
 
 
Output
 
Output
Thread 13 is running
+
Thread 13 is running
Thread 11 is running
+
Thread 11 is running
Thread 12 is running
+
Thread 12 is running
Thread 15 is running
+
Thread 15 is running
Thread 14 is running
+
Thread 14 is running
Thread 18 is running
+
Thread 18 is running
Thread 17 is running
+
Thread 17 is running
Thread 16 is running
+
Thread 16 is running
Thread Class vs Runnable Interface  
+
 
 +
==Thread Class vs Runnable Interface==
 +
 
 +
* Jika kita meng-extend class Thread, class kita tidak dapat meng-extend class lain karena Java tidak mendukung multiple inheritance. Namun, jika kita mengimplementasikan Runnable interface, Class kita masih dapat memperluas Class dasar lainnya.
 +
* Kita dapat mencapai fungsionalitas dasar sebuah thread dengan memperluas Class Thread karena ia menyediakan beberapa inbuilt method seperti yield(), interupsi() dll. yang tidak tersedia di Runnable interface.
 +
* Menggunakan runnable akan memberi object yang dapat dibagikan di antara banyak Thread.
  
If we extend the Thread class, our class cannot extend any other class because Java doesn’t support multiple inheritance. But, if we implement the Runnable interface, our class can still extend other base classes.
 
We can achieve basic functionality of a thread by extending Thread class because it provides some inbuilt methods like yield(), interrupt() etc. that are not available in Runnable interface.
 
Using runnable will give you an object that can be shared amongst multiple threads.
 
  
  

Latest revision as of 07:26, 12 May 2022

Multithreading adalah fitur Java yang memungkinkan eksekusi bersamaan dari dua atau lebih bagian program untuk pemanfaatan CPU secara maksimal. Setiap bagian dari program tersebut disebut thread. Jadi, thread adalah proses ringan dalam suatu proses.

Thread dapat dibuat dengan menggunakan dua mekanisme:

  • Memperluas Thread class
  • Implementing Runnable Interface


Create Thread dengan cara meng-extend Thread class

Kita membuat Class yang memperluas Class java.lang.Thread. Class ini override method run() yang tersedia di Class Thread. Sebuah Thread memulai kehidupannya di dalam method run(). Kita membuat object Class baru dan memanggil metode start() untuk memulai eksekusi Thread. Start() memanggil metode run() pada object Thread.

// Java code for thread creation by extending
// the Thread class
class MultithreadingDemo extends Thread {
    public void run()
    {
        try {
            // Displaying the thread that is running
            System.out.println(
                "Thread " + Thread.currentThread().getId()
                + " is running");
        }
        catch (Exception e) {
            // Throwing an exception
            System.out.println("Exception is caught");
        }
    }
}
 
// Main Class
public class Multithread {
    public static void main(String[] args)
    {
        int n = 8; // Number of threads
        for (int i = 0; i < n; i++) {
            MultithreadingDemo object
                = new MultithreadingDemo();
            object.start();
        }
    }
}

Output

Thread 15 is running
Thread 14 is running
Thread 16 is running
Thread 12 is running
Thread 11 is running
Thread 13 is running
Thread 18 is running
Thread 17 is running

Creat Thread dengan cara meng-implementasi Runnable Interface

Kita membuat Class baru yang mengimplementasikan java.lang.Runnable interface dan override method run(). Kemudian kita membuat instance objek Thread dan memanggil method start() pada object ini.

// Java code for thread creation by implementing
// the Runnable Interface
class MultithreadingDemo implements Runnable {
    public void run()
    {
        try {
            // Displaying the thread that is running
            System.out.println(
                "Thread " + Thread.currentThread().getId()
                + " is running");
        }
        catch (Exception e) {
            // Throwing an exception
            System.out.println("Exception is caught");
        }
    }
}

// Main Class
class Multithread {
    public static void main(String[] args)
    {
        int n = 8; // Number of threads
        for (int i = 0; i < n; i++) {
            Thread object
                = new Thread(new MultithreadingDemo());
            object.start();
        }
    }
}

Output

Thread 13 is running
Thread 11 is running
Thread 12 is running
Thread 15 is running
Thread 14 is running
Thread 18 is running
Thread 17 is running
Thread 16 is running

Thread Class vs Runnable Interface

  • Jika kita meng-extend class Thread, class kita tidak dapat meng-extend class lain karena Java tidak mendukung multiple inheritance. Namun, jika kita mengimplementasikan Runnable interface, Class kita masih dapat memperluas Class dasar lainnya.
  • Kita dapat mencapai fungsionalitas dasar sebuah thread dengan memperluas Class Thread karena ia menyediakan beberapa inbuilt method seperti yield(), interupsi() dll. yang tidak tersedia di Runnable interface.
  • Menggunakan runnable akan memberi object yang dapat dibagikan di antara banyak Thread.


Referensi