2 threads in one class java

How to Create and Start Multiple Threads in Java? — Example Tutorial

Hello guys, Multithreading is one of the biggest strengths of Java, which allows you to divide a task and execute faster by using more than one thread. In order to use multiple threads in Java, you need to first define the task which will be executed by those threads. In order to create those tasks, you can either use the Runnable or Callable interface. If you are just learning Java chose the Runnable interface, it’s a simpler one, but if you are familiar with Java multithreading and want to leverage additional features offered by Callable like it can throw an exception and it can also return value, then go ahead and use the Callable interface. Once you have the task ready, you need to create an instance of the Thread class.

You can create as many instances as you want, Java will allow that, but you should be aware of your resources. Generally, you shouldn’t create too many Thread instances in Java because both JVM and the Operating system have a limit on how many threads you can create in Java.

Crossing that limit will result in an error like java.lang.OutOfmemoryError: could not create a native thread, which is rare but quite possible in a highly multi-threaded environment like a web server.

Читайте также:  Declare interfaces in java

Btw, for the purpose of this tutorial and example, creating just three threads are enough.

Let’s assume we create threads T1, T2, and T3. While creating we pass them an instance of your Task class, which extends Runnable. Always remember, you cannot pass an instance of an arbitrary class, you must pass either Callable or Runnable .

Any code which is written in the run() or the call() will then be executed by the thread you passed your task to. The key thing to note is that the thread which passes the code is different than the thread which executes the code. This is where multiple threads come into the picture.

Btw, you can also use thread pools to create multiple threads but that’s a little bit advanced topic and we’ll discuss in some other article if you are curious you can join these best Java Multithreading courses to learn more about how to achieve effective multithreading

How to start a Thread in Java? Example

You might already know that just creating an instance of java.lang.Thread class doesn’t start a new thread, you need to start each thread manually by calling the start() method of the Thread class. This method first creates a thread and then calls the run() method of the Runnable task you have passed to this new thread.

If you directly call the run() method then the code will be executed in the same thread on which you called the run() method, multi-threading or concurrency will not be achieved, as I have explained previously in my article difference between the start and run method of thread in Java.

This is also one of the common multi-threading mistakes many Java developers make. As Brian Goetz has right put creating a concurrent application is never easy despite the best effort of library, frameworks, and Java programming language itself.

As I said, you further join a Java multithreading course like Java Fundamentals — Concurrency with Multithreading on Pluaralsight to learn more about Threads in Java. It also covers advanced multi-threading concepts like thread pools and how to use concurrency utilities like CountDownLatch , CyclicBarrier, or Phaser in Java applications.

How to use Multiple Threads in Java - Example

Java Program to Create and Run a Thread

Here is a Java Program to demonstrate how to use thread by first creating an instance of java.lang.Thread class and later by calling the start method.

/** * Simple Java program to demonstrate how to use multiple threads. * Steps to use * multiple threads in Java : * 1. Implement Runnable interface to put the code * you want to run in separate thread. * 2. Create an Instance of Thread class by * passing an instance of Runnable you just created. * 3. Call Thread.start() * method, this will execute the code in separate thread. * * @author WINDOWS 8 * */ public class MultipleThreadDemo < private static class ParallelTask implements Runnable < @Override public void run() < System.out.println(Thread.currentThread().getName() + " is executing this code"); > > public static void main(String[] args) < // created three threads but none will start until you call // start() method Thread t1 = new Thread(new ParallelTask(), "Thread - T1"); Thread t2 = new Thread(new ParallelTask(), "Thread - T2"); Thread t3 = new Thread(new ParallelTask(), "Thread - T3"); // now, let's start all three threads t1.start(); t2.start(); t3.start(); > > Output Thread - T1 is executing this code Thread - T3 is executing this code Thread - T2 is executing this code

Once a Thread finishes the last line of code inside the run() method or it came out of the run() method by using the return statement or it came out of run() due to an exception being thrown, the thread is finished.

As you might already know you can not reuse this thread again. Calling the start() method on such thread will result in IllegalThreadStateException .

Here is a nice diagram that explains the lifecycle of a thread in Java, you can see different states of thread in Java, and if you want to learn see a threading course like Multithreading and Parallel Computing in Java from Udemy. It’s a great course to learn the multithreading basics and become a better Java developer.

How to create and run thread in Java

Also, when you start multiple threads at the same time in Java, there is no guarantee that which thread will start execution first. It is possible that T3 starts processing before T1 even when you call the start() method on T1 first. This is the job of the Thread scheduler.

That’s all about how to use multiple threads in Java. As I said, there are many ways but this is the simplest way to use more than one thread in your Java program. Once you learn the basics, you can explore more advanced topics like thread-pool which is a more standard and sophisticated way to leverage multiple threads for processing data in Java programs.

If you want to learn more here are some useful resources to learn multithreading in Java in depth.

  • 5 Courses to Learn Java Multithreading in-depth (courses)
  • Difference between volatile, synchronized, and atomic variable in Java (answer)
  • 10 Java Multithreading and Concurrency Best Practices (article)
  • Top 5 Books to Master Concurrency in Java (books)
  • How to do inter-thread communication in Java using wait-notify? (answer)
  • How to pause a Thread in Java? (solution)
  • Top 50 Multithreading and Concurrency Questions in Java (questions)
  • How to avoid deadlock in Java? (answer)
  • Difference between CyclicBarrier and CountDownLatch in Java? (answer)
  • Understanding the flow of data and code in Java program (answer)
  • How to join two threads in Java? (answer)
  • Difference between Executor and ExecutorService in Java? (answer)
  • How to stop a Thread in Java? (answer)
  • Difference between ForkJoinPool and Executor Framework in Java(answer)
  • 5 Essential Skills to Crack Java Interviews (skills)
  • What is Happens Before in Java Concurrency? (answer)

Thanks a lot for reading this article so far. If you like this example of creating multiple threads in Java then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.

P. S. — If you are serious to improve your Java Multithreading and Concurrency Skills but looking for a free course to start with then I also, suggest you check out this awesome free Java Multithreading course on Udemy.

Источник

How to Run Multiple Threads in Java at the Same Time

This article was co-authored by wikiHow staff writer, Darlene Antonelli, MA. Darlene Antonelli is a Technology Writer and Editor for wikiHow. Darlene has experience teaching college courses, writing technology-related articles, and working hands-on in the technology field. She earned an MA in Writing from Rowan University in 2012 and wrote her thesis on online communities and the personalities curated in such communities.

This article has been viewed 8,125 times.

This wikiHow will teach you how to run multiple threads in Java. You’ll want to run multiple threads to create a program that processes multiple actions at once; the more CPU your computer has, the more processes it can run concurrently.

Image titled 12477945 1

Image titled 12477945 2

Thread(Runnable threadObj, String threadName); 
  • ‘ threadObj ‘ is the class that starts the runnable thread and ‘ threadName ‘ is the name of the thread.

Image titled 12477945 3

class RunnableDemo implements Runnable  private Thread t; private String threadName; RunnableDemo( String name)  threadName = name; System.out.println("Creating " + threadName ); > public void run()  System.out.println("Running " + threadName ); try  for(int i = 4; i > 0; i--)  System.out.println("Thread: " + threadName + ", " + i); // Let the thread sleep for a while. Thread.sleep(50); > > catch (InterruptedException e)  System.out.println("Thread " + threadName + " interrupted."); > System.out.println("Thread " + threadName + " exiting."); > public void start ()  System.out.println("Starting " + threadName ); if (t == null)  t = new Thread (this, threadName); t.start (); > > > public class TestThread  public static void main(String args[])  RunnableDemo R1 = new RunnableDemo( "Thread-1"); R1.start(); RunnableDemo R2 = new RunnableDemo( "Thread-2"); R2.start(); > > 

Image titled 12477945 4

Creating Thread-1 Starting Thread-1 Creating Thread-2 Starting Thread-2 Running Thread-1 Thread: Thread-1, 4 Running Thread-2 Thread: Thread-2, 4 Thread: Thread-1, 3 Thread: Thread-2, 3 Thread: Thread-1, 2 Thread: Thread-2, 2 Thread: Thread-1, 1 Thread: Thread-2, 1 Thread Thread-1 exiting. Thread Thread-2 exiting. 

Источник

Оцените статью