Concurrency in easy way - part 2
Computer science graduate.
Previous, blog ( Concurrency in easy way - part 1 ), analog the balls as the threads. First, let know about the process.
A process generally has a complete, private set of basic run-time resources; in particular, each process has its own memory space. And threads are lightweight processes. Analogy if process is a PM, thread can be think as CM of a country.
More simple way, thread is a task which are involved in program. Both processes and threads provide an execution environment, but creating a new thread requires fewer resources than creating a new process.
In java, there are two ways to create threads for concurrency application.
First way
Controlling the thread management directly.
Extending the Thread Class:
Create a new class by extending the
Threadclass.Override the
run()method to define the code executed by the thread.Instantiate your thread class and call its
start()method to begin execution.class MyThread extends Thread { public void run() { System.out.println("Thread Started Running..."); } } public class Main { public static void main(String[] args) { MyThread t1 = new MyThread(); t1.start(); // Starts the thread, which executes run() } }
Implementing the Runnable Interface:
Create a class that implements the
Runnableinterface.Implement the
run()method to specify the thread task.Pass an instance of this class to a
Threadconstructor.Call the
start()method on theThreadobject to run it.class MyRunnable implements Runnable { public void run() { System.out.println("Thread is Running Successfully"); } } public class Main { public static void main(String[] args) { MyRunnable runnable = new MyRunnable(); Thread t1 = new Thread(runnable); t1.start(); } }
Second Way
Abstracting the thread management ( indirectly ) by Java Executor Framework.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolExample {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
int taskNo = i;
executorService.submit(() -> {
System.out.println("Running task " + taskNo + " on thread " + Thread.currentThread().getName());
});
}
executorService.shutdown();
}
}
Note
Here, the thread & process context according to Java Programming language.
More details of Executors framework will be covered later.
PM - Prime Minister, CM - Chief Minister.
