Java is a multi-threaded programming language which means we can develop multi-threaded program using Java. A multi-threaded program contains two or more parts that can run concurrently and each part can handle a different task at the same time making optimal use of the available resources specially when your computer has multiple CPUs.

By definition, multitasking is when multiple processes share common processing resources such as a CPU. Multi-threading extends the idea of multitasking into applications where you can subdivide specific operations within a single application into individual threads. Each of the threads can run in parallel. The OS divides processing time not only among different applications, but also among each thread within an application.

Multi-threading enables you to write in a way where multiple activities can proceed concurrently in the same program.

Life Cycle of a Thread

A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and then dies. The following diagram shows the complete life cycle of a thread.

Following are the stages of the life cycle −

  • New − A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread.

  • Runnable − After a newly born thread is started, the thread becomes runnable. A thread in this state is considered to be executing its task.

  • Waiting − Sometimes, a thread transitions to the waiting state while the thread waits for another thread to perform a task. A thread transitions back to the runnable state only when another thread signals the waiting thread to continue executing.

  • Timed Waiting − A runnable thread can enter the timed waiting state for a specified interval of time. A thread in this state transitions back to the runnable state when that time interval expires or when the event it is waiting for occurs.

  • Terminated (Dead) − A runnable thread enters the terminated state when it completes its task or otherwise terminates.

Thread Priorities

Every Java thread has a priority that helps the operating system determine the order in which threads are scheduled.

Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5).

Threads with higher priority are more important to a program and should be allocated processor time before lower-priority threads. However, thread priorities cannot guarantee the order in which threads execute and are very much platform dependent.

Create a Thread by Implementing a Runnable Interface

If your class is intended to be executed as a thread then you can achieve this by implementing a Runnable interface. You will need to follow three basic steps −

Step 1

As a first step, you need to implement a run() method provided by a Runnable interface. This method provides an entry point for the thread and you will put your complete business logic inside this method. Following is a simple syntax of the run() method −

public void run( )

Step 2

As a second step, you will instantiate a Thread object using the following constructor −

Thread(Runnable threadObj, String threadName);

Where, threadObj is an instance of a class that implements the Runnableinterface and threadName is the name given to the new thread.

Step 3

Once a Thread object is created, you can start it by calling start() method, which executes a call to run( ) method. Following is a simple syntax of start() method −

void start();

Example

Here is an example that creates a new thread and starts running it −

Live Demo

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();
}
}

This will produce the following result −

Output

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.

Create a Thread by Extending a Thread Class

The second way to create a thread is to create a new class that extends Thread class using the following two simple steps. This approach provides more flexibility in handling multiple threads created using available methods in Thread class.

Step 1

You will need to override run( ) method available in Thread class. This method provides an entry point for the thread and you will put your complete business logic inside this method. Following is a simple syntax of run() method −

public void run( )

Step 2

Once Thread object is created, you can start it by calling start() method, which executes a call to run( ) method. Following is a simple syntax of start() method −

void start( );

Example

Here is the preceding program rewritten to extend the Thread −

Live Demo

class ThreadDemo extends Thread {
private Thread t;
private String threadName; ThreadDemo( 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[]) {
ThreadDemo T1 = new ThreadDemo( "Thread-1");
T1.start(); ThreadDemo T2 = new ThreadDemo( "Thread-2");
T2.start();
}
}

This will produce the following result −

Output

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.

Thread Methods

Following is the list of important methods available in the Thread class.

Sr.No. Method & Description
1

public void start()

Starts the thread in a separate path of execution, then invokes the run() method on this Thread object.

2

public void run()

If this Thread object was instantiated using a separate Runnable target, the run() method is invoked on that Runnable object.

3

public final void setName(String name)

Changes the name of the Thread object. There is also a getName() method for retrieving the name.

4

public final void setPriority(int priority)

Sets the priority of this Thread object. The possible values are between 1 and 10.

5

public final void setDaemon(boolean on)

A parameter of true denotes this Thread as a daemon thread.

6

public final void join(long millisec)

The current thread invokes this method on a second thread, causing the current thread to block until the second thread terminates or the specified number of milliseconds passes.

7

public void interrupt()

Interrupts this thread, causing it to continue execution if it was blocked for any reason.

8

public final boolean isAlive()

Returns true if the thread is alive, which is any time after the thread has been started but before it runs to completion.

The previous methods are invoked on a particular Thread object. The following methods in the Thread class are static. Invoking one of the static methods performs the operation on the currently running thread.

Sr.No. Method & Description
1

public static void yield()

Causes the currently running thread to yield to any other threads of the same priority that are waiting to be scheduled.

2

public static void sleep(long millisec)

Causes the currently running thread to block for at least the specified number of milliseconds.

3

public static boolean holdsLock(Object x)

Returns true if the current thread holds the lock on the given Object.

4

public static Thread currentThread()

Returns a reference to the currently running thread, which is the thread that invokes this method.

5

public static void dumpStack()

Prints the stack trace for the currently running thread, which is useful when debugging a multithreaded application.

Example

The following ThreadClassDemo program demonstrates some of these methods of the Thread class. Consider a class DisplayMessage which implements Runnable −

// File Name : DisplayMessage.java
// Create a thread to implement Runnable public class DisplayMessage implements Runnable {
private String message; public DisplayMessage(String message) {
this.message = message;
} public void run() {
while(true) {
System.out.println(message);
}
}
}

Following is another class which extends the Thread class −

// File Name : GuessANumber.java
// Create a thread to extentd Thread public class GuessANumber extends Thread {
private int number;
public GuessANumber(int number) {
this.number = number;
} public void run() {
int counter = 0;
int guess = 0;
do {
guess = (int) (Math.random() * 100 + 1);
System.out.println(this.getName() + " guesses " + guess);
counter++;
} while(guess != number);
System.out.println("** Correct!" + this.getName() + "in" + counter + "guesses.**");
}
}

Following is the main program, which makes use of the above-defined classes −

// File Name : ThreadClassDemo.java
public class ThreadClassDemo { public static void main(String [] args) {
Runnable hello = new DisplayMessage("Hello");
Thread thread1 = new Thread(hello);
thread1.setDaemon(true);
thread1.setName("hello");
System.out.println("Starting hello thread...");
thread1.start(); Runnable bye = new DisplayMessage("Goodbye");
Thread thread2 = new Thread(bye);
thread2.setPriority(Thread.MIN_PRIORITY);
thread2.setDaemon(true);
System.out.println("Starting goodbye thread...");
thread2.start(); System.out.println("Starting thread3...");
Thread thread3 = new GuessANumber(27);
thread3.start();
try {
thread3.join();
} catch (InterruptedException e) {
System.out.println("Thread interrupted.");
}
System.out.println("Starting thread4...");
Thread thread4 = new GuessANumber(75); thread4.start();
System.out.println("main() is ending...");
}
}

This will produce the following result. You can try this example again and again and you will get a different result every time.

Output

Starting hello thread...
Starting goodbye thread...
Hello
Hello
Hello
Hello
Hello
Hello
Goodbye
Goodbye
Goodbye
Goodbye
Goodbye
.......

Java - Multithreading zz的更多相关文章

  1. Java 多线程 (转)

    http://www.ibm.com/developerworks/cn/java/j-thread/index.html http://www.ibm.com/developerworks/cn/j ...

  2. Core Java Interview Question Answer

    This is a new series of sharing core Java interview question and answer on Finance domain and mostly ...

  3. Java 程序中的多线程

    概述 synchronized  关键字,代表这个方法加锁,相当于不管哪一个线程(例如线程A),运行到这个方法时,都要检查有没有其它线程B(或者C. D等)正在用这个方法,有的话要等正在使用synch ...

  4. java url demo

    // File Name : URLDemo.java import java.net.*; import java.io.*; public class URLDemo { public stati ...

  5. Java基础之用记事本编辑java代码运行,并且打成jar包后运行

    使用记事本写java代码 1.在d盘新建一个记事本,名字叫做zhanzhuang.java,会询问不可用,是否继续,点击是 2.在里面编辑就如下内容,注意文件的名字要和 class 后面的名字相对应 ...

  6. 200个最常见的JAVA面试问题(附答案)

    本文内容: 20个最常见的JAVA面试问题(附答案) 13个单例模式JAVA面试问题(附答案) 说说JVM和垃圾收集是如何工作的(附答案) 说说如何避免JAVA线程死锁(附答案) Java中HashS ...

  7. java多线程编码注意事项

    Sole purpose of using concurrency is to produce scalable and faster program. But always remember, sp ...

  8. Java Callable Future Example(java 关于Callable,Future的例子)

    Home » Java » Java Callable Future Example Java Callable Future Example April 3, 2018 by Pankaj 25 C ...

  9. 五分钟学会悲观乐观锁-java vs mysql vs redis三种实现

    1 悲观锁乐观锁简介 乐观锁( Optimistic Locking ) 相对悲观锁而言,乐观锁假设认为数据一般情况下不会造成冲突,所以在数据进行提交更新的时候,才会正式对数据的冲突与否进行检测,如果 ...

随机推荐

  1. Python高级笔记(一) -- GIL (全局解释器锁)

    1. GIL概念 (cpython历史遗留问题) 概念? 对Python多线程的影响? 编写一个多线程抓取网页的程序? 阐述多线程抓取程序是否比单线程性能有提升, 并解释原因. GIL:全局解释器锁, ...

  2. kubernetes包管理工具Helm安装

    helm官方建议使用tls,首先生成证书. openssl genrsa -out ca.key.pem openssl req -key ca.key.pem -new -x509 -days -s ...

  3. file 多次上传附件功能完善

    之前解决了一个页面中的单个附件上传问题,使用的是 id 定位.但是一个页面中,可能存在多个附件上传的地方,这时候如果继续使用 id,会出问题. 我依旧会上传一个附件.附件链接地址: https://f ...

  4. <HTML>初识HTML

    最近在阅读Head first HTML and CSS, 写一些笔记.   小知识: 1. 浏览器会忽略HTML文档中的制表符,回车和大部分空格——要用标记 2. WYSIWYG——使得用户在视图中 ...

  5. JAVA的运算符和条件结构

    一.JAVA的运算符. 1.赋值运算符 赋值就是把一个变量的值赋给另一个变量. 语法: 变量名=表达式     例如  n = m + 5 2.算术运算符      算术运算符是数学中常用的加.减.乘 ...

  6. spring.http.multipart.maxFileSize提示无效报错问题处理

    在SpringBoot项目中,配置spring.http.multipart.maxFileSize用于限定最大文件上传大小. 但是,SpringBoot版本不同,关于这一块的配置也不相同. 1.Sp ...

  7. 解锁技能:sass + node-sass多页面应用编译(转载)

    传送门:https://blog.csdn.net/wx11408115/article/details/78023466

  8. golang包管理工具glide安装

    1:下载安装glide go get github.com/Masterminds/glide glide的源码以及exe文件在第一个gopath目录,如果不知道哪个是第一个gopath,echo一下 ...

  9. 2018-2019 网络对抗技术 20165231 Exp5 MSF基础应用

    实践内容(3.5分) 本实践目标是掌握metasploit的基本应用方式,重点常用的三种攻击方式的思路.具体需要完成: 1.1一个主动攻击实践(1分) ms08_067; (失败) MS17-010永 ...

  10. L2-011 玩转二叉树 (25 分) (树)

    链接:https://pintia.cn/problem-sets/994805046380707840/problems/994805065406070784 题目: 给定一棵二叉树的中序遍历和前序 ...