Saturday, 10 June 2017

Java Tutorial: Java Threads (How to execute multiple tasks by multiple threads - anonymous class) ~ foundjava


Click here to watch in Youtube : 

MultitaskingThread.java
/*
 * How to perform multiple tasks by multiple threads
 * (multitasking in multithreading)?
 * 
 * Program of performing two tasks by two threads
 */
public class MultitaskingThread
{

    public static void main(String args[]) throws InterruptedException
    {
        /*
         * annonymous class that extends Thread class
         */
        Thread t1 = new Thread()
        {
            public void run()
            {
                System.out.println("task 1 run by = "
                        + Thread.currentThread().getName());
            }
        };
        /*
         * annonymous class that extends Thread class
         */
        Thread t2 = new Thread()
        {
            public void run()
            {
                System.out.println("task 2 run by = "
                        + Thread.currentThread().getName());
            }
        };

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

    }

}
Output
task 1 run by = Thread-0
task 2 run by = Thread-1
MultitaskingRunnable.java
/*
 * How to perform multiple tasks by multiple threads
 * (multitasking in multithreading)?
 * 
 * Program of performing two tasks by two threads
 */
public class MultitaskingRunnable
{

    public static void main(String[] args)
    {
        /*
         * annonymous class that implements Runnable
         * interface
         */
        Runnable r1 = new Runnable()
        {
            public void run()
            {
                System.out.println("task 1 run by = "
                        + Thread.currentThread().getName());
            }
        };
        /*
         * annonymous class that implements Runnable
         * interface
         */
        Runnable r2 = new Runnable()
        {
            public void run()
            {
                System.out.println("task 2 run by = "
                        + Thread.currentThread().getName());
            }
        };

        Thread t1 = new Thread(r1);
        Thread t2 = new Thread(r2);

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

    }

}
Output
task 1 run by = Thread-0
task 2 run by = Thread-1

Click the below link to download the code:

CLICK HERE

No comments:

Post a Comment