Java 中的线程
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2865315/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Threads in Java
提问by Kevin
I was today asked in an interview over the Thread concepts in Java? The Questions were...
今天我在接受采访时被问到 Java 中的线程概念?问题是...
- What is a thread?
- Why do we go for threading?
- A real time example over the threads.
- Can we create threads in Spring framework service class.
- Can flex call a thread?
- 什么是线程?
- 我们为什么要进行线程化?
- 线程上的实时示例。
- 我们可以在 Spring 框架服务类中创建线程吗?
- flex 可以调用线程吗?
I did not answer any questions apart from definition of Thread, that too I just learnt from internet.
除了 Thread 的定义之外,我没有回答任何问题,这也是我刚刚从互联网上学到的。
Can anyone explain me clearly over this.
任何人都可以解释清楚这一点。
Update:
更新:
What is a difference between a thread and a normal java class. why do we need threading... can i execute business logic in threads. Can i call a different class methods in Threads.
线程和普通的 java 类有什么区别。为什么我们需要线程......我可以在线程中执行业务逻辑吗?我可以在线程中调用不同的类方法吗?
采纳答案by Sajad Bahmani
To create threads, create a new class that extends the Thread
class, and instantiate that class. The extending class must override the run
method and call the start
method to begin execution of the thread.
要创建线程,请创建一个扩展Thread
类的新类,然后实例化该类。扩展类必须覆盖该run
方法并调用该start
方法以开始执行线程。
Inside run
, you will define the code that constitutes a new thread. It is important to understand that run
can call other methods, use other classes and declare variables just like the main thread. The only difference is that run
establishes the entry point for another, concurrent thread of execution within your program. This will end when run
returns.
在里面run
,您将定义构成新线程的代码。run
可以像主线程一样调用其他方法、使用其他类和声明变量,理解这一点很重要。唯一的区别是run
为程序中的另一个并发执行线程建立入口点。这将在run
返回时结束。
Here's an example:
下面是一个例子:
public class MyThread extends Thread {
private final String name;
public MyThread(String name) {
this.name = name;
}
public void run() {
try {
for (; ; ) {
System.out.println(name);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("sleep interrupted");
}
}
public static void main(String[] args) {
Thread t1 = new MyThread("First Thread");
Thread t2 = new MyThread("Second Thread");
t1.start();
t2.start();
}
}
You will see this on the screen:
您将在屏幕上看到:
First Thread
Second Thread
First Thread
Second Thread
First Thread
This tutorialalso explains the Runnable
interface. With Spring, you could use a thread pool.
回答by Steve
I can answer the first 3 since I'm not too familiar with the threading features of Spring or Flex.
我可以回答前 3 个,因为我不太熟悉 Spring 或 Flex 的线程特性。
A thread is an object that has its own registers and stack that can run parallel with other threads in a process (a process is a collection of threads).
You write multi-threaded code for the program to be responsiveto user interactions. Think of how annoying it would be if you had to wait for your browser to finish downloading a file before you can continue browsing.
I gave an example in #2. Other examples are any programs with a GUI (the GUI has to always be responsive to user input while performing background tasks), or server type software such as a web server where you might have to respond to 1000 requests a minute. It would be better to have a separate thread for each of those responses.
线程是具有自己的寄存器和堆栈的对象,可以与进程中的其他线程并行运行(进程是线程的集合)。
您为程序编写多线程代码以响应用户交互。想想如果您必须等待浏览器完成下载文件才能继续浏览,那该有多烦人。
我在#2中举了一个例子。其他示例是具有 GUI 的任何程序(在执行后台任务时,GUI 必须始终响应用户输入),或服务器类型的软件,例如 Web 服务器,您可能每分钟必须响应 1000 个请求。最好为每个响应设置一个单独的线程。
回答by Stephen C
As far as Spring is concerned, yes you can definitely create your own threads. But it is a better idea to use the thread pool support described in Chapter 25of the Spring Framework Manual.
就 Spring 而言,是的,您绝对可以创建自己的线程。但是使用Spring Framework Manual 的第 25 章中描述的线程池支持是一个更好的主意。
However, having requests spawn threads in a Spring-based web service (or any web service for that matter) introduces resource management issues that you may want to avoid ...
但是,让请求在基于 Spring 的 Web 服务(或任何与此相关的 Web 服务)中产生线程会引入您可能想要避免的资源管理问题......
回答by pdbartlett
One key concept to clear up is that a thread is an OS scheduling object, which just happens to have a Java class that represents it (as, say, Window would in the UI sub-system). Threads are not themselves a type of class.
需要澄清的一个关键概念是线程是一个操作系统调度对象,它恰好有一个代表它的 Java 类(例如,Window 在 UI 子系统中)。线程本身不是一种类。
回答by mezmo
Flex cannot directly communicate with Java threads, there would have to be some sort of messaging whether you use JMS or whatever, Flex via BlazeDS, GraniteDS, or LCDS can communicate with JMS. One thing to remember as well is that, at the moment anyway, Flash/Flex itself is single threaded, but highly asynchronous....some would say TOO asynchronous...so any use of Java threads to speed things up may not have as great an effect as you might hope for.
Flex 不能直接与 Java 线程通信,无论您使用 JMS 还是其他方式,都必须有某种消息传递,Flex 通过 BlazeDS、GraniteDS 或 LCDS 可以与 JMS 通信。还需要记住的一件事是,目前无论如何,Flash/Flex 本身是单线程的,但高度异步......有些人会说太异步......所以任何使用 Java 线程来加速的可能都没有与您希望的一样大的效果。
回答by roottraveller
Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilisation of CPU. Each part of such program is called a thread. So,
多线程是一种 Java 特性,它允许同时执行程序的两个或多个部分,以最大限度地利用 CPU。这种程序的每一部分都称为一个线程。所以,
Threads are light-weight processes within a process.
线程是进程中的轻量级进程。
Threads can be created by using two mechanisms :
可以使用两种机制创建线程:
- Extending the Thread class
- Implementing the Runnable Interface
- 扩展 Thread 类
- 实现 Runnable 接口
Thread creation by extending the Thread class
通过扩展Thread类创建线程
We create a class that extends the java.lang.Thread
class. This class overrides the run()
method available in the Thread
class. A thread begins its life inside run()
method. We create an object of our new class and call start()
method to start the execution of a thread. Start()
invokes the run()
method on the Thread
object.
我们创建一个扩展java.lang.Thread
类的类。该类覆盖了该类中run()
可用的方法Thread
。线程在run()
方法内开始其生命周期。我们创建一个新类的对象并调用start()
方法来启动线程的执行。Start()
调用对象的run()
方法Thread
。
class MultithreadingDemo extends Thread{
public void run() {
try { // Displaying the thread that is running
System.out.println ("Thread " + Thread.currentThread().getId()
+ " is running");
}
catch (Exception e){ // Throwing an exception
System.out.println ("Exception is caught");
}
}
}
public class Multithread{
public static void main(String[] args) {
int n = 8; // Number of threads
for (int i=0; i<8; i++) {
MultithreadingDemo object = new MultithreadingDemo();
object.start();
}
}
}
Thread creation by implementing the Runnable Interface
通过实现 Runnable 接口创建线程
We create a new class which implements java.lang.Runnable
interface and override run()
method. Then we instantiate a Thread object and call start()
method on this object.
我们创建了一个实现java.lang.Runnable
接口和覆盖run()
方法的新类。然后我们实例化一个 Thread 对象并start()
在这个对象上调用方法。
class MultithreadingDemo implements Runnable{
public void run() {
try { // Displaying the thread that is running
System.out.println ("Thread " + Thread.currentThread().getId() +
" is running");
}
catch (Exception e) { // Throwing an exception
System.out.println ("Exception is caught");
}
}
}
class Multithread{
public static void main(String[] args) {
int n = 8; // Number of threads
for (int i=0; i<8; i++) {
Thread object = new Thread(new MultithreadingDemo());
object.start();
}
}
}
Thread Class vs Runnable Interface
线程类与可运行接口
If we extend the Thread class, our class cannot extend any other class because Java doesn't support multiple inheritance. But, if we implement the Runnable interface, our class can still extend other base classes.
We can achieve basic functionality of a thread by extending Thread class because it provides some inbuilt methods like yield(), interrupt() etc. that are not available in Runnable interface.
如果我们扩展 Thread 类,我们的类不能扩展任何其他类,因为 Java 不支持多重继承。但是,如果我们实现 Runnable 接口,我们的类仍然可以扩展其他基类。
我们可以通过扩展 Thread 类来实现线程的基本功能,因为它提供了一些 Runnable 接口中没有的内置方法,如 yield()、interrupt() 等。
回答by Ravindra babu
Have a look oracle tutorial
看看oracle教程
- What is a thread?
- 什么是线程?
Threads are sometimes called lightweight processes. Threads exist within a process — every process has at least one. Threads share the process's resources, including memory and open files. This makes for efficient, but potentially problematic, communication.
线程有时被称为轻量级进程。线程存在于一个进程中——每个进程至少有一个。线程共享进程的资源,包括内存和打开的文件。这有助于实现高效但可能存在问题的沟通。
Why do we go for threading?
Multithreaded execution is an essential feature of the Java platform. Threads are independent of each other.
You can parallelize your computation by breaking into multiple sub computations.
You can use CPU cores of your server effectively.
e.g.
ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime() .availableProcessors());
if you follow shared-nothing approach ( which is not possible always) between your threads, multi-threading application provides high throughput.
A real time example over the threads.
Think of WhatsApp kind of a chat application.
The server should send and receive chat messages among thousands of users. A single threaded application is disaster to handle this use case.
我们为什么要进行线程化?
多线程执行是 Java 平台的一个基本特性。线程是相互独立的。
您可以通过分解为多个子计算来并行化您的计算。
您可以有效地使用服务器的 CPU 内核。
例如
ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime() .availableProcessors());
如果您在线程之间遵循无共享方法(这并不总是可能的),多线程应用程序将提供高吞吐量。
线程上的实时示例。
想想 WhatsApp 类型的聊天应用程序。
服务器应该在数千个用户之间发送和接收聊天消息。单线程应用程序处理这个用例是灾难性的。
What is a difference between a thread and a normal java class. why do we need threading... can i execute business logic in threads. Can i call a different class methods in Threads.
线程和普通的 java 类有什么区别。为什么我们需要线程......我可以在线程中执行业务逻辑吗?我可以在线程中调用不同的类方法吗?
A Thread class can implement Runnableor extend Thread. Have a look at oracle tutorial page
Thread 类可以实现Runnable或扩展Thread。看看oracle教程页面
You can execute business logic in Threads.
您可以在线程中执行业务逻辑。
You can call different class methods in Threads.
您可以在线程中调用不同的类方法。
回答by Faraz Shaikh
Ok to answer what is thread in java in simple word its a program/piece of code which works simultaneously with your normal class. A difference between a normal class and a thread is that a thread works simultaneously its works parallely along with the normal class. In more simpler terms lets see a example where i am currently in main function and requires a function to compute something . so if that function is not in a thread then the function will be evaluated first and after then i will return to main function on the other hand if it is a thread then the function will compute and main will will also compute its next instruction.
好的,用简单的词来回答什么是 java 中的线程,它是一个程序/一段代码,它与您的普通类同时工作。普通类和线程之间的区别在于,线程与普通类并行工作。用更简单的术语来说,让我们看一个例子,我目前在 main 函数中,需要一个函数来计算某些东西。因此,如果该函数不在线程中,则该函数将首先被评估,然后我将返回到 main 函数,另一方面,如果它是一个线程,则该函数将计算并且 main 还将计算其下一条指令。
Now as to how a thread is created
1. extend thread class: extend thread class and write start()
its a function call it using an object of current class and write a function namely void run()
and in this function write the code which needs to be performed concurrently.
现在关于如何创建线程 1.扩展线程类:扩展线程类并编写start()
一个函数,使用当前类的对象调用它并编写一个函数,void run()
并在该函数中编写需要并发执行的代码。
Each object of the class which extends thread is a customized thread.by default every thread is inactive and to activate or call that thread just write start()
this will automatically call run which contains your code.
扩展线程的类的每个对象都是一个自定义线程。默认情况下,每个线程都处于非活动状态,要激活或调用该线程,只需编写start()
这将自动调用包含您的代码的运行。
class MyThreads extends Thread
{
int ch ;
MyThreads(int p)
{
ch = p;
start();//statement to activate thread and call run
}
public void run()
{
if(ch == 1)
functionx()
else if(ch == 2)
functiony();
}
void fx1()
{
//parallel running code here
}
void fx2()
{
//parallel running code here
}
public static void main(String args[])
{
MyThreads obj1 = new MyThreads(1);
My3Threads obj2 = new MyThreads(2);
//mains next instruction code here
}
}
- you can also implement a interface namely
Runnable
but as this is a interface which is compatible with the current class so calling start will call the functionrun()
which is written in interface but as to call ourrun()
function call the start with a thread object like thisThread t=new thread(this); t.start();
- 你也可以实现一个接口,
Runnable
但因为这是一个与当前类兼容的接口,所以调用 start 将调用run()
写在接口中的函数,但调用我们的run()
函数调用 start 与这样的线程对象Thread t=new thread(this); t.start();
Now to why do we go for thread,this is just like asking why do we go for multicore processor you get what I am saying, multi threading is used to execute task concurrently
现在我们为什么要使用线程,这就像问我们为什么要使用多核处理器一样,您明白我在说什么,多线程用于并发执行任务
A real time example would be a server any server ,consider the server of Gmail.So if g mail server was not written using multi threading then i could not log in without you logging out which means in the whole world only one person can login at one time you see how impractical it is.
一个实时的例子是一个服务器,任何服务器,考虑 Gmail 的服务器。所以如果 g 邮件服务器不是使用多线程编写的,那么我无法在没有您注销的情况下登录,这意味着在整个世界中只有一个人可以登录有一次你会发现这是多么不切实际。
回答by Swati Gour
http://learningsolo.com/multithreading/
http://learningsolo.com/multithreading/
Multithreading is the process of executing two or more threads concurrently in a single program. Single core processor can execute one thread at a time but OS uses the time slicing feature to share processor time. Thread is a light weight process. The thread exists in the process and requires less resources to create. It shares the process resources. When the java application starts, it creates the first user thread for main which in turn spawn's multiple user threads and daemon thread. The thread scheduler schedules the thread execution. When the work of all the threads are done, the JVM terminates the application.
多线程是在单个程序中同时执行两个或多个线程的过程。单核处理器一次可以执行一个线程,但操作系统使用时间切片功能来共享处理器时间。线程是一个轻量级的进程。线程存在于进程中,需要较少的资源来创建。它共享进程资源。当 java 应用程序启动时,它会为 main 创建第一个用户线程,然后生成多个用户线程和守护线程。线程调度器调度线程执行。当所有线程的工作完成后,JVM 终止应用程序。
Every java application has at least one thread – main thread. Although, there are so many other java threads running in background like memory management, system management, signal processing etc. But from application point of view – main is the first java thread and we can create multiple threads from it.
每个java应用程序至少有一个线程——主线程。虽然,在后台运行着很多其他的 java 线程,比如内存管理、系统管理、信号处理等。但是从应用程序的角度来看——main 是第一个 java 线程,我们可以从中创建多个线程。