900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > java 多线程使用线程池_Java多线程:如何开始使用线程

java 多线程使用线程池_Java多线程:如何开始使用线程

时间:2020-06-14 16:28:23

相关推荐

java 多线程使用线程池_Java多线程:如何开始使用线程

java 多线程使用线程池

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

A thread is a lightweight process. Any process can have multiple threads running in it.

线程是轻量级进程。 任何进程都可以在其中运行多个线程。

For example in a web browser, we can have one thread which will load the user interface and another thread which will actually retrieve all the data that needs to be displayed in that interface.

例如,在Web浏览器中,我们可以有一个线程将加载用户界面,而另一个线程将实际检索需要在该界面中显示的所有数据。

什么是多线程? (What is MultiThreading?)

Multithreading enables us to run multiple threads concurrently.

多线程使我们能够同时运行多个线程。

For example in a web browser, we can have one thread which handles the user interface, and in parallel we can have another thread which fetches the data to be displayed.

例如,在Web浏览器中,我们可以有一个线程来处理用户界面,而并行地,我们可以有另一个线程来获取要显示的数据。

So multithreading improves the responsiveness of a system.

因此,多线程可提高系统的响应能力。

什么是并发? (What is Concurrency?)

Concurrency in the context of threads enables us to run multiple threads at the same time.

线程上下文中的并发性使我们可以同时运行多个线程。

But do the threads really run at the same time?

但是这些线程真的同时运行吗?

单核系统 (Single Core Systems)

TheThread Schedulerprovided by the JVM decides which thread runs at any given time. The scheduler gives a small time slice to each thread.

JVM提供的线程计划程序决定在任何给定时间运行哪个线程。 调度程序为每个线程分配了一小段时间。

So at any given time we have only one thread which is actually running in the processor. But because of the time slicing we get the feeling that multiple threads are running at the same time.

因此,在任何给定时间,我们只有一个线程在处理器中实际运行。 但是由于时间片,我们感觉到多个线程正在同时运行。

多核系统 (Multi Core Systems)

Even in multiple core systems the thread scheduler is involved. But since we have multiple cores, we can actually have multiple threads running at the exact same time.

即使在多核系统中,也要使用线程调度程序。 但是,由于我们有多个内核,因此实际上我们可以在完全相同的时间运行多个线程。

For example if we have a dual core system, then we can have 2 threads running at the exact same time. The first thread will run in the first core, and the second thread will run in the second core.

例如,如果我们有一个双核系统,那么我们可以有两个线程同时运行。 第一个线程将在第一个内核中运行,第二个线程将在第二个内核中运行。

为什么需要多线程? (Why is Multithreading needed?)

Multithreading enables us to improve the responsiveness of a system.

多线程使我们能够改善系统的响应能力。

For example in a web browser, if everything ran in a single thread, then system would be completely unresponsive whenever data was being fetched to display. For example, if it takes 10 seconds to fetch the data, then in that 10 seconds we wont be able to do anything else in the web browser like opening new tabs, or even closing the web browser.

例如,在Web浏览器中,如果所有内容都在单个线程中运行,那么只要提取数据以进行显示,系统就会完全无响应。 例如,如果获取数据需要10秒钟,那么在那10秒钟内,我们将无法在Web浏览器中执行其他任何操作,例如打开新标签页,甚至关闭Web浏览器。

So running different parts of a program in different threads concurrently helps improve the responsiveness of a system.

因此,在不同线程中同时运行程序的不同部分有助于提高系统的响应能力。

如何用Java编写多线程程序 (How to write Multithreaded Programs in Java)

We can create threads in Java using the following

我们可以使用以下代码在Java中创建线程

Extending the thread class扩展线程类 Implementing the runnable interface实施可运行接口 Implementing the callable interface实现可调用的接口 By using the executor framework along with runnable and callable tasks通过使用执行程序框架以及可运行和可调用的任务

We will look at callables and the executor framework in a separate blog. In this article I will be mainly focussing on extending the thread class and implementing the runnable interface.

我们将在单独的博客中介绍可调用对象和执行程序框架。 在本文中,我将主要集中于扩展线程类和实现可运行接口。

扩展线程类 (Extending the Thread Class)

In order to create a piece of code which can be run in a thread, we create a class and then extend thethreadclass. The task being done by this piece of code needs to be put in therun()function.

为了创建可以在线程中运行的代码,我们创建一个类,然后扩展该线程类。 由这段代码完成的任务需要放在run()函数中。

In the below code you can see thatworkeris a class which extends thethreadclass, and the task of printing numbers 0 to 5 is being done inside therun()function.

在下面的代码中,您可以看到worker是扩展线程类的类,并且在run()函数中完成了打印数字0至5的任务。

class Worker extends Thread {@Overridepublic void run() {for (int i = 0; i <= 5; i++) {System.out.println(Thread.currentThread().getName() + ": " + i);}}}

In the above codeThread.currentThread().getName()is used to get the name of the current thread which is running the code.

在上面的代码中,Thread.currentThread()。getName()用于获取运行代码的当前线程的名称。

In order to create athread, we just need to create an instance of the worker class. And then we can start the thread using thestart()function.

为了创建线程,我们只需要创建worker类的实例。 然后,我们可以使用start()函数启动线程。

public class ThreadClassDemo {public static void main(String[] args) {Thread t1 = new Worker();Thread t2 = new Worker();Thread t3 = new Worker();t1.start();t2.start();t3.start();}}

In the above code, we are creating 3 threads (t1,t2 and t3) from the worker class. Then we are starting the threads using thestart()function.

在上面的代码中,我们从worker类创建3个线程(t1,t2和t3)。 然后,我们使用start()函数启动线程。

Here is the final code for creating a thread by extending a thread class:

这是通过扩展线程类创建线程的最终代码:

class Worker extends Thread {@Overridepublic void run() {for (int i = 0; i <= 5; i++) {System.out.println(Thread.currentThread().getName() + ": " + i);}}}public class ThreadClassDemo {public static void main(String[] args) {Thread t1 = new Worker();Thread t2 = new Worker();Thread t3 = new Worker();t1.start();t2.start();t3.start();}}

Here is the output we get by running the above code:

这是通过运行上面的代码获得的输出:

You can see that all the 3 threads have printed the numbers from 0 to 5.

您可以看到所有3个线程都已打印从0到5的数字。

You can also clearly see from the output that the 3 threads do not run in any particular sequence

您还可以从输出中清楚地看到3个线程没有按任何特定顺序运行

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

In order to create a piece of code which can be run in a thread, we create a class and then implement therunnableinterface. The task being done by this piece of code needs to be put in therun()function.

为了创建可以在线程中运行的代码,我们创建一个类,然后实现可运行接口。 由这段代码完成的任务需要放在run()函数中。

In the below code you can see thatRunnableWorkeris a class which implementsrunnableinterface, and the task of printing numbers 0 to 4 is being done inside therun()function.

在下面的代码中,您可以看到RunnableWorker是实现runnable接口的类,并且在run()函数内部完成了打印数字0至4的任务。

class RunnableWorker implements Runnable{@Overridepublic void run() {for (int i = 0; i <= 4; i++) {System.out.println(Thread.currentThread().getName() + ": " + i);}}}

In order to create a thread, first we need to create an Instance ofRunnableWorkerwhich implements therunnableinterface.

为了创建一个线程,首先我们需要创建RunnableWorker的实例,实现Runnable接口。

Then we can create a new thread by creating an instance of thethreadclass and passing the instance ofRunnableWorkeras the argument. This is shown in the code below:

然后,我们可以通过创建线程类的实例并将RunnableWorker的实例作为参数来创建新线程。 如下代码所示:

public class RunnableInterfaceDemo {public static void main(String[] args) {Runnable r = new RunnableWorker();Thread t1 = new Thread(r);Thread t2 = new Thread(r);Thread t3 = new Thread(r);t1.start();t2.start();t3.start();}}

The above code creates a runnable instance r. Then it create 3 threads (t1, t2 and t3) and passesras the argument to the 3 threads. Then thestart()function is used to start all 3 threads.

上面的代码创建了一个可运行实例r。 然后,它创建3个线程(t1,t2和t3),并将r作为参数传递给3个线程。 然后使用start()函数启动所有3个线程。

Here is the complete code for creating a thread by implementing the runnable interface:

这是用于通过实现runnable接口创建线程的完整代码:

class RunnableWorker implements Runnable{@Overridepublic void run() {for (int i = 0; i <= 4; i++) {System.out.println(Thread.currentThread().getName() + ": " + i);}}}public class RunnableInterfaceDemo {public static void main(String[] args) {Runnable r = new RunnableWorker();Thread t1 = new Thread(r);Thread t2 = new Thread(r);Thread t3 = new Thread(r);t1.start();t2.start();t3.start();}}

On running the above code, we will get the following output. The sequence of the output will change every time the code is run.

运行上面的代码后,我们将获得以下输出。 每次运行代码时,输​​出顺序都会改变。

Implementing the runnable interface is a better option than extending the thread class since we can extend only one class, but we can implement multiple interfaces in Java.

与只能扩展一个线程类相比,实现可运行接口是更好的选择,因为我们只能扩展一个类,但是我们可以在Java中实现多个接口。

Java 8中的可运行接口 (Runnable Interface in Java 8)

In Java 8, the runnable interface becomes aFunctionalInterfacesince it has only one function,run().

在Java 8中,由于可运行接口只有一个函数run(),因此它成为FunctionalInterface

The below code shows how we can create a runnable instance in Java 8.

以下代码显示了我们如何在Java 8中创建可运行实例。

public class RunnableFunctionalInterfaceDemo {public static void main(String[] args) {Runnable r = () -> {for (int i = 0; i <= 4; i++) {System.out.println(Thread.currentThread().getName() + ": " + i);}};Thread t1 = new Thread(r);Thread t2 = new Thread(r);Thread t3 = new Thread(r);t1.start();t2.start();t3.start();}}

Here, instead of creating a class and then implementing the runnable interface, we can directly use a lambda expression to create a runnable instance as shown below:

在这里,我们可以直接使用lambda表达式创建一个可运行的实例,而不是创建一个类然后再实现可运行的接口,如下所示:

Runnable r = () -> {for (int i = 0; i <= 4; i++) {System.out.println(Thread.currentThread().getName() + ": " + i);}};

码 (Code)

The code in this article is available in the following GitHub repo: /aditya-sridhar/basic-threads-demo

以下GitHub存储库中提供了本文中的代码: https : ///aditya-sridhar/basic-threads-demo

恭喜😃 (Congrats 😃)

You now know how to create threads by extending the thread class and by implementing the runnable interface.

现在,您知道如何通过扩展线程类并实现可运行接口来创建线程。

I will discuss the thread life cycle and challenges while using threads in my next blog post.

我将在下一篇博客文章中讨论使用线程时的线程生命周期和挑战。

My Website: /

我的网站: https : ///

随时在LinkedIn上与我联系或在Twitter上关注我 (Feel free to connect with me on LinkedIn or follow me on Twitter)

翻译自: /news/how-to-get-started-with-multithreading-in-java/

java 多线程使用线程池

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。