Friday, 27 January 2017

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


Click here to watch in Youtube : 
https://www.youtube.com/watch?v=iF4B2H14PTI&list=UUhwKlOVR041tngjerWxVccw

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:
https://sites.google.com/site/ramj2eev1/home/javabasics/ThreadDemo_MultipleTask_MT_App.zip?attredirects=0&d=1

Github Link:
https://github.com/ramram43210/Java/tree/master/BasicJava/ThreadDemo_MultipleTask_MT_App

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/c72ef0bb7cf33f5c158c45d824df234766210e9a/BasicJava/ThreadDemo_MultipleTask_MT_App/?at=master

See also:
  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • All JAVA EE Links
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • No comments:

    Post a Comment

    Google+ Followers

    Google+ Badge