Java Thread Programming: Lesson 1

Posted on by

Categories:         

When we run a java program, we are given an execution environment that runs our code one by one. When we have only one execution environment, things are pretty straightforward. All the code runs the same way we write. However, when we have many things to run simultaneously, this single environment will not help us much. That’s where Thread comes into the picture.

We can write our program in a way; it can do multiple things simultaneously in different threads. Each Thread is a unique execution environment.

Creating a thread is easy. In java, we have a class called Thread that can be instantiated and provided a job to it, and it will run independently. Let’s see an example- T

package com.bazlur.threads;

public class Playground {
  public static void main(String[] args) {
    Thread thread1 = new Thread(() -> {
      System.out.println("Running from: " + Thread.currentThread());
    });

    Thread thread2 = new Thread(() -> {
      System.out.println("Running from: " + Thread.currentThread());
    });

    thread1.start();
    thread2.start();
  }
}

When we create a thread, we pass a lambda expression to its argument. In the expression, we put our code that we want to run independently.

In the above code, we have created two threads. Each Thread will run independently and simultaneously. Although we have started two threads one by one, we can never tell which one would run first. That’s the nature of the Thread. They are independent and depend on how the operating system schedules them to run.

So far, we have just seen how to create a thread and how to run them. They are super helpful when we have some independent work to be done. For example- we have to write a web server where multiple clients connect to it. If the server runs with a single thread, then at a time, it will be able only to serve one client. That’s not super useful. The server should handle multiple clients at a time, and that’s the point of having it.

Let’s see in the code-

package com.bazlur.threads;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Playground {
  public static void main(String[] args) throws IOException {
    var serverSocket = new ServerSocket(4040);
    System.out.println("Started server on port " + 4040);

    while (true) {
      var socket = serverSocket.accept();
      var thread = new Thread(() -> {
        handleClient(socket);
      });
      thread.start();
    }
  }

  private static void handleClient(Socket socket) {
    //here we have code for handling a client
  }
}

In the above code, the server keeps listening from clients, and whenever a client connects, it creates a new thread and passes the job into it. That’s how threads help us.

That’s for today, cheers!!

           

Share on:

Author: A N M Bazlur Rahman

Java Champion | Software Engineer | JUG Leader | Book Author | InfoQ & Foojay.IO Editor | Jakarta EE Ambassadors| Helping Java Developers to improve their coding & collaboration skills so that they can meet great people & collaborate

100daysofcode 100daysofjava access advance-java agile algorithm arraylist article bangla-book becoming-expert biginteger book calculator checked checked-exceptions cloning code-readability code-review coding coding-convention collection-framework compact-strings completablefuture concatenation concurrency concurrentmodificationexception concurrentskiplistmap counting countingcollections critical-section daemon-thread data-race data-structure datetime day002 deliberate-practice deserialization design-pattern developers duration execute-around executors export fibonacci file file-copy fork/join-common-pool functional future-java-developers groupby hash-function hashmap history history-of-java how-java-performs-better how-java-works http-client image import inspiration io itext-pdf java java-10 java-11 java-17 java-8 java-9 java-developers java-performance java-programming java-thread java-thread-programming java11 java16 java8 lambda-expression learning learning-and-development linkedlist list local-type-inference localdatetime map methodology microservices nio non-blockingio null-pointer-exception object-cloning optional packaging parallel pass-by-reference pass-by-value pdf performance prime-number programming project-loom race-condition readable-code record refactoring review scheduler scrum serialization serversocket simple-calculator socket software-development softwarearchitecture softwareengineering sorting source-code stack string string-pool stringbuilder swing thread threads tutorial unchecked vector virtual-thread volatile why-java zoneid