java多线程_Java | 多线程

java多线程

Concurrent execution of multiple programs at a time (running Word and Chrome simultaneously) is Multiprogramming. Likewise, execution of multiple tasks ( processes, programs, threads etc.) at a time is Multitasking. The major difference between them is, multi-programming works solely on the concept of context switching, whereas multi-tasking is based on time sharing.

一次同时执行多个程序(同时运行Word和Chrome)是Multiprogramming 同样,一次执行多个任务(进程,程序,线程等)就是“ 多任务处理” 。 它们之间的主要区别在于,多编程仅基于上下文切换的概念工作,而多任务则基于时间共享。

Multithreading is a process of concurrent execution of two or more parts of a program, for maximum utilization of CPU. Also, Multithreading is an extension of multitasking, where you can sub-divide specific operations within a single application, into individual threads. Each of these threads can run in parallel. The Operating System divides processing time, not only among different applications, but also among each thread within an application. It enables you to write a program in a way where multiple activities can proceed concurrently.

多线程是并发执行程序的两个或更多部分的过程,以最大程度地利用CPU。 同样, 多线程是多任务的扩展,您可以在其中将单个应用程序中的特定操作细分为各个线程。 这些线程中的每一个都可以并行运行。 操作系统不仅在不同的应用程序之间分配处理时间,还在应用程序中的每个线程之间分配处理时间。 它使您可以以可以同时进行多个活动的方式编写程序。

什么是线程? (What is Thread?)

A thread is basically a light-weight process and Java provides built-in support for a multithreaded programming. A Multithreaded Program is one, that contains two or more parts that can run concurrently. Each part of such program is called Thread. Every thread defines a separate path of execution.

线程基本上是一个轻量级的进程,而Java为多线程编程提供了内置支持。 多线程程序是一个多线程程序 ,它包含两个或多个可以同时运行的部分。 这种程序的每个部分都称为Thread 。 每个线程都定义了单独的执行路径。

The Main() method in Java is also executed on a special thread, which is created by the Java Virtual Machine to run your application. From inside your application, you can create and start more threads, which can execute parts of your application utilities in parallel with the main thread. Yet another point to remember is, Threads running in parallel does not actually means they are running at the same instance. The control of accessing the processor is switched between threads. These threads although runs on a single processor and share common resources.

Java中的Main()方法也在特殊线程上执行,该线程由Java虚拟机创建以运行您的应用程序。 在应用程序内部,您可以创建和启动更多线程,这些线程可以与主线程并行执行应用程序实用程序的各个部分。 需要记住的另一点是, 并行运行线程实际上并不意味着它们在同一实例上运行。 访问处理器的控制在线程之间切换 。 这些线程虽然在单个处理器上运行并共享公共资源。

线程的生命周期: (Life cycle of a Thread:)

A thread goes through numerous stages like, a thread is born, starts, runs and then eventually dies. Life cycle of thread:

线程经历了多个阶段,例如,线程诞生,启动,运行,然后最终死亡。 线程的生命周期:

New: A thread begins its life cycle at this stage. The thread remains in the new state until the program starts it.

新增:线程在此阶段开始其生命周期。 线程保持新状态,直到程序启动它为止。

Runnable: As the program starts the new thread, the thread becomes runnable. Thread at this stage is considered to be executing its part of application, when the processor is available.

可运行在程序启动新线程时,该线程变为可运行。 当处理器可用时,此阶段的线程被视为正在执行其应用程序的一部分。

Running: When the processor gives time to thread, for execution, the thread is said to be in Running state.

正在运行:当处理器给线程留出时间执行时,该线程被称为处于运行状态。

Waiting: When the thread waits for another thread to perform a task, the thread is said to be in waiting state. This is goes back to the running state , as soon as it receive signal from the running thread to continue execution.

等待中:当线程等待另一个线程执行任务时,该线程被称为处于等待状态。 一旦它从正在运行的线程中接收到信号以继续执行,就回到运行状态。

Blocked: When thread is prevented from entering the running state or runnable state, due to its suspension or sleep, the thread is considered to be in blocked state.

阻塞:如果由于线程的挂起或睡眠而导致线程无法进入运行状态或可运行状态,则认为该线程处于阻塞状态。

Dead: The thread enters this state when it completes the execution of task. The thread is terminated at this state.

死:线程在完成任务执行后进入此状态。 线程在此状态下终止。

创建一个线程: (Creating a Thread:)

Threads can be creating using 2 mechanisms:

可以使用2种机制来创建线程:

  1. Implementing the Runnable Interface.

    实现可运行接口。
  2. Extending the Thread class.

    扩展Thread类。

实现可运行接口: (Implementing the Runnable Interface:)

For this mechanism, we need to create a class that implements Runnable interface. Since, the class will be implementing the Runnable interface, we need to define all the methods, declared in the interface. Luckily, Runnable interface got only one method declared in it, that is, run() method. So we need to define the run method in our class.

对于这种机制,我们需要创建一个实现Runnable接口的类。 由于该类将实现Runnable接口,因此我们需要定义在接口中声明的所有方法。 幸运的是,Runnable接口仅在其中声明了一个方法,即run()方法。 因此,我们需要在类中定义run方法。

Once we are done with this, we only need to instantiate our class, create an object of Thread and pass the reference of the object of our class for the constructor of the Thread class, and call the start() method of the thread class. Start method will then load the run() method of the class whose reference was received through the constructor. And hence, run method of our class will be executed on a separate thread.

完成此操作后,我们仅需实例化我们的类,创建Thread对象,并将该对象的引用传递给Thread类的构造函数,然后调用线程类的start()方法。 然后,Start方法将加载通过构造函数接收其引用的类的run()方法。 因此,我们类的run方法将在单独的线程上执行。

class MyThread implements Runnable{public void run(){try{
// Displaying the running thread
System.out.println("Thread " + Thread.currentThread().getId() + " is running..");}catch(Exception exception){
System.out.println(exception.getMessage()); // Exception handling
}
}
}class Multithreading{public static void main(String args[]){for(int i = 1 ; i <= 5 ; i++) {//Instantiating Thread
Thread thread=new Thread(new MyThread());// loads the run method of MyThread class
thread.start();
}
}
}

Compile and execute the above code multiple time and you will be witnessing the different output, each time you execute it. The output at my machine looked like this.

多次编译并执行上述代码,每次执行时,您都会看到不同的输出。 我机器上的输出看起来像这样。

Image for post
Difference in output each time is proof of concept for Multithreading
每次输出的差异是多线程概念的证明

扩展Thread类: (Extending the Thread class:)

For this mechanism, we need to create a class that extends java.lang.Thread class. The Thread class implements the Runnable interface and hence, would have defined the run method in it. So this time, we just need to override the run method in our class.

对于这种机制,我们需要创建一个扩展java.lang.Thread类的类。 Thread类实现了Runnable接口,因此将在其中定义run方法。 所以这一次,我们只需要重写类中的run方法。

Once we have designed the class with run method, we will instantiate it and call the start() method. Since we haven’t written a start method, according to Java rules, start method of Thread class will be executed, which will stack up the run method of our class and eventually the part of application in the run method will be executed.

一旦使用run方法设计了类,就将其实例化并调用start()方法。 由于尚未编写启动方法,因此根据Java规则,将执行Thread类的启动方法,这将堆积我们类的run方法,并最终执行该应用程序中run方法的一部分。

class MyThread extends Thread{public void run(){try{
// Displaying the running thread
System.out.println("Thread " + Thread.currentThread().getId() + " is running..");}catch(Exception exception){
System.out.println(exception.getMessage()); // Exception handling
}
}
}class Multithreading{public static void main(String args[]){for(int i = 1 ; i <= 5 ; i++) {//Instantiating Thread
MyThread myThread=new MyThread();// load the run method of MyThread class
myThread.start();
}
}
}

Compile and execute this as done previously and you will be again witnessing the randomized output every time you execute it. And this is the proof of concept of Multithreading.

像以前一样编译并执行此操作,每次执行时,您将再次目睹随机输出。 这就是多线程概念的证明。

一些有用的线程方法: (Some useful Thread methods:)

We can use number of thread methods for performing our action, but some favourable methods are described below. These methods are static method, and invoking this performs the action on the currently running thread.

我们可以使用多种线程方法来执行操作,但是下面介绍了一些有利的方法。 这些方法是静态方法 ,调用此方法会对当前正在运行的线程执行操作。

  1. public static void getAllStackTraces(): returns a map containing Thread mapped to an array that represents the stack trace of the corresponding thread.

    public static void getAllStackTraces() :返回包含Thread的映射,该映射映射到表示相应线程的堆栈跟踪的数组。

  2. public static boolean holdsLock(Object): returns true if and only if, the current thread holds the monitor lock on the specified object.

    public static boolean holdLock(Object) :仅当当前线程在指定对象上持有监视器锁时,才返回true。

  3. public static Thread currentThread(): returns the reference to the currently executing thread.

    公共静态线程currentThread() :返回对当前正在执行的线程的引用。

  4. public static int activeCount(): returns an estimate of the number of active threads in the current thread group.

    public static int activeCount ():返回当前线程组中活动线程数的估计值。

  5. public static void sleep(millis): causes the currently executing thread to temporarily cease execution, for the specified number of milliseconds.

    public static void sleep(millis) :使当前正在执行的线程在指定的毫秒数内暂时停止执行。

Some more useful non-static methods are :

一些更有用的非静态方法是:

  1. public long getId(): returns the identifier of this Thread.

    public long getId() :返回此线程的标识符。

  2. public void start(): causes this thread to begin execution by stacking up the run method of the corresponding class.

    public void start() :使该线程通过堆积相应类的run方法开始执行。

  3. public final void join(): waits for this thread to terminate.

    public final void join() :等待该线程终止。

  4. public void run(): if thread is instantiated using either by extending the Thread class, or by implementing the runnable interface, then this method is called. If defined, it contains a part of the application code.

    public void run() :如果通过扩展Thread类或通过实现runnable接口来实例化线程,则将调用此方法。 如果定义,它将包含应用程序代码的一部分。

  5. public final void setPriority(int): sets the priority of this Thread. Priority can vary from 1 to 10, where 1 being the highest priority and 10 being the least priority.

    public final void setPriority(int) :设置此线程的优先级。 优先级可以在1到10之间变化,其中1是最高优先级,而10是最低优先级。

线程优先级: (Thread Priority:)

Each thread has a priority. Thread scheduler assigns processor to each thread based on this priority. Priority can either be given by JVM or it can be given by programmer explicitly. The priority can range from 1 to 10. There are 3 more static variables defined in Thread class for priority.

每个线程都有一个优先级。 线程调度程序根据此优先级将处理器分配给每个线程。 优先级可以由JVM赋予,也可以由程序员明确赋予。 优先级的范围可以从1到10。在Thread类中还有3个静态变量定义优先级。

public static int MAX_PRIORITY: The maximum priority that a thread can have.public static int MIN_PRIORITY: The minimum priority that a thread can have.public static int NORM_PRIORITY: The default priority that is assigned to a thread.

优先级的有用方法: (Useful methods for priority:)

  1. public final int getPriority(): Returns this thread’s priority.

    public final int getPriority() :返回此线程的优先级。

  2. public final void setPriority(int priority): Changes the priority of this thread. This method throws IllegalArgumentException if value of priority goes beyond minimum(1) and maximum(10) limit.

    public final void setPriority(int priority) :更改此线程的优先级。 如果优先级的值超过最小(1)和最大(10)限制,则此方法引发IllegalArgumentException

Below is the code and its output will help in better understanding of the same:

以下是代码及其输出将有助于更好地理解它们:

import java.lang.*; 
class MyThread extends Thread {public void run() {
System.out.println("Run method invoked.."); }
}class Multithreading {
public static void main(String args[]) {MyThread thread1= new MyThread();
MyThread thread2 = new MyThread();
MyThread thread3 = new MyThread();//Default priority is 5
System.out.println("Priority of thread1 : "+ thread1.getPriority());
System.out.println("Priority of thread2 : "+ thread2.getPriority());
System.out.println("Priority of thread3 : "+ thread3.getPriority());//Setting priority
thread1.setPriority(2);
thread2.setPriority(5);
thread3.setPriority(8);// thread3.setPriority(11);
//will throw IllegalArgumentExceptionSystem.out.println("Priority of thread1 : "+ thread1.getPriority());
System.out.println("Priority of thread2 : "+ thread2.getPriority());
System.out.println("Priority of thread3 : "+ thread3.getPriority());System.out.println("Priority of Main thread : " + Thread.currentThread().getPriority());
}
}

Compile and execute the above code as done previously and your output must look like:

像以前一样编译并执行上述代码,您的输出必须类似于:

Image for post
Thread Priority
线程优先级

线程异常: (Thread Exceptions:)

When an exception occurs, the normal flow of the program gets disrupted and the program terminates abnormally, which is not recommended, therefore, these exceptions needs to be handled. Some of the commonly used exceptions, are:

发生异常时,程序的正常流程会中断,程序会异常终止,因此不建议这样做,因此,需要处理这些异常 。 一些常用的例外是:

Sleep() method gives rise to:

Sleep()方法产生:

IllegalArgumentExceptionInterruptedException

start() method gives rise to:

start()方法产生:

IllegalThreadStateException

Some other exceptions can be namely:

其他一些例外可以是:

  1. SecurityException

    SecurityException
  2. NullPointerException

    空指针异常
  3. NoSuchMethodError

    NoSuchMethodError

线程安全性: (Thread Safety:)

In Multithreading, several threads are executed simultaneously, so odds may be that they might access the same resource. This act can lead to sharing of resources by multiple threads at the same time, leading to inconsistent change in the data. This can create enormous problem when implemented in any project. So, this chaos is solved by using a Thread-safety process. In this process, a thread, working on an object, prevents other threads from working on the same object, hence providing a Thread-safe code.

在多线程中,多个线程同时执行,因此可能会访问相同的资源。 此行为可能导致多个线程同时共享资源,从而导致数据更改不一致。 当在任何项目中实施时,这可能会带来巨大的问题。 因此,可以通过使用线程安全过程来解决此混乱情况。 在此过程中,在对象上工作的线程会阻止其他线程在同一对象上工作,因此提供了线程安全的代码。

同步: (Synchronization:)

Synchronization is a way of achieving Thread safety. It allows only one thread to complete the particular task. It can be implemented using a synchronized keyword, which is a modifier that creates a block of code known as a critical section. Below is the code for implementing it:

同步是一种实现线程安全的方法。 它仅允许一个线程来完成特定任务。 可以使用synced关键字来实现它,它是一个修饰符,可创建称为关键部分的代码块。 下面是实现它的代码:

class Sync {

synchronized void sum(int n) {
// Creating a thread instance
Thread thread = Thread.currentThread();
for (int i = 1; i <= 5; i++) System.out.println("Processing "+thread.getName() + " : " + (n + i));
}
}class MyThread extends Thread { // Creating an object of class Sync for accessing resource
Sync sync=new Sync();
public void run() {
sync.sum(10);
}
}class Multithreading {public static void main(String args[]) {//Instantiating MyThread class
MyThread myThread=new MyThread();//Instantiating thread instances
Thread thread1 = new Thread(myThread);
Thread thread2 = new Thread(myThread);
thread1.setName("Thread A");
thread2.setName("Thread B");// Starting thread instance thread1 and thread2
thread1.start();
thread2.start();
}
}

Compile and execute without and with synchronize keyword and your output will look like this, respectively:

编译和执行不带关键字和带同步关键字的情况,您的输出将分别如下所示:

Image for post
Without and With synchronize keyword
不使用和使用同步关键字

结论: (Conclusion:)

In this article, we learned what are threads, what is Multithreading, ways of creating threads, some utilities from Thread class, its priority, exceptions and safety. Hope you find it helpful and feel free to add comment/notes for any suggestions or questions.

在本文中,我们了解了什么是线程,什么是多线程,创建线程的方法,Thread类中的一些实用程序,其优先级,异常和安全性。 希望对您有所帮助,并随时为任何建议或问题添加评论/注释。

Thank You!

谢谢!

翻译自: https://medium.com/swlh/java-multithreading-48a21a361791

java多线程

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值