Saturday, 10 June 2017

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


Click here to watch in Youtube : 

MultitaskingThread.java
class TaskOneThread extends Thread
{
    TaskOneThread(String threadName)
    {
        super(threadName);
    }

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

class TaskTwoThread extends Thread
{

    TaskTwoThread(String threadName)
    {
        super(threadName);
    }

    public void run()
    {
        System.out.println("task 2 run by = " + this.getName());
    }
}

/*
 * 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
    {
        TaskOneThread t1 = new TaskOneThread("Task One Thread");
        TaskTwoThread t2 = new TaskTwoThread("Task two Thread");

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

}
Output
task 1 run by = Task One Thread
task 2 run by = Task two Thread

MultitaskingRunnable.java
class TaskOneRunnable implements Runnable
{
    
    public void run()
    {
        System.out.println("task 1 run by = "
                + Thread.currentThread().getName());
    }
}
class TaskTwoRunnable implements Runnable
{
    public void run()
    {
        System.out.println("task 2 run by = "
                + Thread.currentThread().getName());
    }
}

public class MultitaskingRunnable
{

    public static void main(String[] args)
    {
        TaskOneRunnable taskOneRunnable = new TaskOneRunnable();
        TaskTwoRunnable taskTwoRunnable = new TaskTwoRunnable();

        Thread t1 = new Thread(taskOneRunnable,"Task One Thread");
        Thread t2 = new Thread(taskTwoRunnable,"Task two Thread");

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

    }

}
Output
task 1 run by = Task One Thread
task 2 run by = Task two Thread

Click the below link to download the code:

CLICK HERE

No comments:

Post a Comment