Java Thread I - Creation

Multithreading

Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilization of CPU. Each part of such program is called a thread. So, threads are light-weight processes within a process.

Threads can be created by using two mechanisms:

  1. Extending the Thread class
  2. Implementing the Runnable Interface**

Thread cration by extending the Thread class

  • create a class that extends the java.lang.Thread class
  • override the run() method, a thread begins its life inside run() method.
  • call start() method to start the execution of a thread. Start() invokes the run() method on the Thread object

Example:

public class MyThread extends Thread {
	private String name;
	public MyThread(String name) {
		this.name = name;
	}

	@Override
	public void run() {
		for (int i = 0; i < 10; i++) {
			System.out.println("Thread start: " + this.name + ", i= " + i);
		}
	}
}

public class ThreadDemo {
    public static void main(String[] args) {
        MyThread mt1 = new MyThread("thread1");
        MyThread mt2 = new MyThread("thread2");
        MyThread mt3 = new MyThread("thread3");

        mt1.start();
        mt2.start();
        mt3.start();
    }
}

Thread cration by implementing the Runnable interface

  • create a new class which implements java.lang.Runnable interface
  • override run() method
  • construct an object of the new class
  • instantiate a Thread object from the Runaable: Thread t = new Thread(r)
  • call start() method on this object

Example:

public class MyRunnable implements Runnable {
	private String name;
	public MyRunnable (String name) {
		this.name = name;
	}
	@Override
	public void run() {
		for (int i = 0; i < 10; i++) {
			System.out.println("Thread start: " + this.name + ", i= " + i);
		}
	}
}

public static void main(String[] args) {
	MyRunnable mr1 = new MyRunnable("Runnable1");
	MyRunnable mr2 = new MyRunnable("Runnable2");
	MyRunnable mr3 = new MyRunnable("Runnable3");
	Thread t1 = new Thread(mr1);
	Thread t2 = new Thread(mr2);
	Thread t3 = new Thread(mr3);

	t1.start();
	t2.start();
	t3.start();
}

Supplymentary

java.lang.Thread

  • Thread(Runnable target)
    constructs a new thread that calls the run() method of the specified target
  • void start()
    starts this thread, causing the run() method to be called. This method will return immediately. The new thread runs concurrently.
  • void run()
    calls the run method of the associated Runnable.

java.lang.Runnable

  • void run()
    must be overriden and supplied with instructions for the task that you want to have executed.

   Reprint policy


《Java Thread I - Creation》 by Tong Shi is licensed under a Creative Commons Attribution 4.0 International License
  TOC