Saturday, 10 June 2017

Java Tutorial: Java Threads (How to execute a single task by multiple threads) ~ foundjava


Click here to watch in Youtube :

Click the below Image to Enlarge
Java Tutorial: Java Threads (How to execute a single task by multiple threads) 
MultitaskingThread.java
/*
 * Program of performing single task by multiple threads
 */
public class MultitaskingThread extends Thread
{

    public static void main(String args[]) throws InterruptedException
    {
        MultitaskingThread t1 = new MultitaskingThread();
        MultitaskingThread t2 = new MultitaskingThread();
        MultitaskingThread t3 = new MultitaskingThread();

        t1.start();
        t2.start();
        t3.start();
    }

    /*
     * If you have to perform single task by many threads, have only
     * one run() method.
     */
    public void run()
    {
        System.out.println("task 1" + " Run by = "
                + Thread.currentThread().getName());
    }
}
Output
task 1 Run by = Thread-0
task 1 Run by = Thread-2
task 1 Run by = Thread-1
MultitaskingRunnable.java
/*
 * Program of performing single task by multiple threads
 */
public class MultitaskingRunnable implements Runnable
{

    public static void main(String[] args)
    {
        MultitaskingRunnable multitaskingRunnable = new MultitaskingRunnable();
        Thread t1 = new Thread(multitaskingRunnable);
        Thread t2 = new Thread(multitaskingRunnable);

        t1.start();
        t2.start();

    }

    public void run()
    {
        System.out.println("task 1" + " Run by = "
                + Thread.currentThread().getName());
    }

}
Output
task 1 Run by = Thread-0
task 1 Run by = Thread-1

Click the below link to download the code:

CLICK HERE

No comments:

Post a Comment