Blog

Filter posts by Category Or Tag of the Blog section!

Multithreading in java

Monday, 23 October 2017

I'm not a java developer and I've never worked with java in real products. Sometimes I read and concepts and compare with C#, Java is cool as well! By using multithread you can perform many operations together and the system doesn't block the user until completing the operations. There are two ways for multithreading in java: inhering from a class named Thread and implementing an interface named Runnable. I like Runnable because you have another chance to inherit the class from another class if you would need!

 

public class Multithread implements Runnable  {

    public void run() {

        System.out.println("Thread: " + Thread.currentThread().getId() + " is running");

    }

}

 

class MainClass

{

    public static void main(String[] args)

    {

        int n = 5;

        for (int i=0; i<5; i++)

        {

            Thread object = new Thread(new Multithread());

            object.start();

        }

    }

}

 

If you run this code, the following output will appear:

 

Thread: 8 is running
Thread: 9 is running
Thread: 10 is running
Thread: 11 is running
Thread: 12 is running

Category: Software

Tags: Java

comments powered by Disqus