简体   繁体   English

Java 中的线程

[英]Threads in Java

I was today asked in an interview over the Thread concepts in Java?今天我在接受采访时被问到 Java 中的线程概念? The Questions were...问题是...

  1. What is a thread?什么是线程?
  2. Why do we go for threading?我们为什么要进行线程化?
  3. A real time example over the threads.线程上的实时示例。
  4. Can we create threads in Spring framework service class.我们可以在 Spring 框架服务类中创建线程吗?
  5. Can flex call a thread? 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.线程和普通的 java 类有什么区别。 why do we need threading... can i execute business logic in threads.为什么我们需要线程......我可以在线程中执行业务逻辑吗? Can i call a different class methods in Threads.我可以在线程中调用不同的类方法吗?

To create threads, create a new class that extends the Thread class, and instantiate that class.要创建线程,请创建一个扩展Thread类的新类,然后实例化该类。 The extending class must override the run method and call the start method to begin execution of the thread.扩展类必须覆盖run方法并调用start方法以开始执行线程。

Inside run , you will define the code that constitutes a new thread.run ,您将定义构成新线程的代码。 It is important to understand that run can call other methods, use other classes and declare variables just like the main thread.理解run可以像主线程一样调用其他方法、使用其他类和声明变量很重要。 The only difference is that run establishes the entry point for another, concurrent thread of execution within your program.唯一的区别是run为程序中的另一个并发执行线程建立了入口点。 This will end when run returns.这将在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 tutorial also explains the Runnable interface. 本教程还解释了Runnable接口。 With Spring, you could use a thread pool .使用 Spring,您可以使用线程池

Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilisation of CPU.多线程是一种 Java 特性,它允许同时执行程序的两个或多个部分,以最大限度地利用 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扩展 Thread 类
  2. Implementing the Runnable Interface实现 Runnable 接口

Thread creation by extending the Thread class通过扩展Thread类创建线程

We create a class that extends the java.lang.Thread class.我们创建一个扩展java.lang.Thread类的类。 This class overrides the run() method available in the Thread class.此类覆盖了Thread类中可用的run()方法。 A thread begins its life inside run() method.线程在run()方法中开始其生命周期。 We create an object of our new class and call start() method to start the execution of a thread.我们创建一个新类的对象并调用start()方法来启动线程的执行。 Start() invokes the run() method on the Thread object. Start()调用Thread对象上的run()方法。

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.我们创建了一个实现java.lang.Runnable接口并覆盖run()方法的新类。 Then we instantiate a Thread object and call start() method on this object.然后我们实例化一个 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线程类与可运行接口

  1. If we extend the Thread class, our class cannot extend any other class because Java doesn't support multiple inheritance.如果我们扩展 Thread 类,我们的类不能扩展任何其他类,因为 Java 不支持多重继承。 But, if we implement the Runnable interface, our class can still extend other base classes.但是,如果我们实现 Runnable 接口,我们的类仍然可以扩展其他基类。

  2. 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 类来实现线程的基本功能,因为它提供了一些 Runnable 接口中没有的内置方法,如 yield()、interrupt() 等。

I can answer the first 3 since I'm not too familiar with the threading features of Spring or Flex.我可以回答前 3 个,因为我不太熟悉 Spring 或 Flex 的线程特性。

  1. 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).线程是具有自己的寄存器和堆栈的对象,可以与进程中的其他线程并行运行(进程是线程的集合)。

  2. You write multi-threaded code for the program to be responsive to 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.想想如果您必须等待浏览器完成下载文件才能继续浏览,那该有多烦人。

  3. I gave an example in #2.我在#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.其他示例是具有 GUI 的任何程序(GUI 必须在执行后台任务时始终响应用户输入),或服务器类型的软件,例如您可能每分钟必须响应 1000 个请求的 Web 服务器。 It would be better to have a separate thread for each of those responses.最好为每个响应设置一个单独的线程。

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).需要澄清的一个关键概念是线程是一个操作系统调度对象,它恰好有一个代表它的 Java 类(例如,Window 在 UI 子系统中)。 Threads are not themselves a type of class.线程本身不是一种类。

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. Flex 不能直接与 Java 线程通信,无论您使用 JMS 还是其他方式,都必须有某种消息传递,Flex 通过 BlazeDS、GraniteDS 或 LCDS 可以与 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.还需要记住的一件事是,无论如何,目前 Flash/Flex 本身是单线程的,但高度异步......有些人会说太异步......所以任何使用 Java 线程来加快速度的可能都没有与您希望的一样大的效果。

As far as Spring is concerned, yes you can definitely create your own threads.就 Spring 而言,是的,您绝对可以创建自己的线程。 But it is a better idea to use the thread pool support described in Chapter 25 of the Spring Framework Manual.但是使用 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 服务)中产生线程会引入您可能想要避免的资源管理问题......

Have a look oracle tutorial看看oracle 教程

  1. 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.这有助于实现高效但可能存在问题的沟通。

  1. Why do we go for threading?我们为什么要进行线程化?

    1. Multithreaded execution is an essential feature of the Java platform.多线程执行是 Java 平台的一个基本特性。 Threads are independent of each other.线程是相互独立的。

    2. You can parallelize your computation by breaking into multiple sub computations.您可以通过分解为多个子计算来并行化您的计算。

    3. You can use CPU cores of your server effectively.您可以有效地使用服务器的 CPU 内核。

    eg例如

    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.如果您在线程之间遵循无共享方法(这并不总是可能的),多线程应用程序将提供高吞吐量。

  2. A real time example over the threads.线程上的实时示例。

    Think of WhatsApp kind of a chat application.想想 WhatsApp 类型的聊天应用程序。

    The server should send and receive chat messages among thousands of users.服务器应该在数千个用户之间发送和接收聊天消息。 A single threaded application is disaster to handle this use case.单线程应用程序处理这个用例是灾难性的。

What is a difference between a thread and a normal java class.线程和普通的 java 类有什么区别。 why do we need threading... can i execute business logic in threads.为什么我们需要线程......我可以在线程中执行业务逻辑吗? Can i call a different class methods in Threads.我可以在线程中调用不同的类方法吗?

A Thread class can implement Runnable or extendThread . Thread 类可以实现Runnable或扩展Thread Have a look at oracle tutorial page看看oracle教程页面

You can execute business logic in Threads.您可以在线程中执行业务逻辑。

You can call different class methods in Threads.您可以在线程中调用不同的类方法。

Ok to answer what is thread in java in simple word its a program/piece of code which works simultaneously with your normal class.好的,用简单的词来回答什么是 java 中的线程,它是一个程序/一段代码,它与您的普通类同时工作。 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 .用更简单的术语来说,让我们看一个示例,其中我目前在 main 函数中并且需要一个函数来计算某些东西。 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.因此,如果该函数不在线程中,则该函数将首先被评估,然后我将返回到 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()这将自动调用包含您的代码的 run。

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

 }
}
  1. 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 function run() which is written in interface but as to call our run() function call the start with a thread object like this Thread t=new thread(this); t.start();您还可以实现一个接口,即Runnable但由于这是一个与当前类兼容的接口,因此调用 start 将调用编写在接口中的函数run() ,但调用我们的run()函数调用 start 与像这样的线程对象Thread t=new thread(this); t.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 邮件服务器不是使用多线程编写的,那么我无法在没有您注销的情况下登录,这意味着在整个世界中只有一个人可以登录有一次你会发现这是多么不切实际。

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.当 java 应用程序启动时,它会为 main 创建第一个用户线程,然后生成多个用户线程和守护线程。 The thread scheduler schedules the thread execution.线程调度器调度线程执行。 When the work of all the threads are done, the JVM terminates the application.当所有线程的工作完成后,JVM 终止应用程序。

Every java application has at least one thread – main thread.每个java应用程序至少有一个线程——主线程。 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 线程,比如内存管理、系统管理、信号处理等。但是从应用程序的角度来看——main 是第一个 java 线程,我们可以从中创建多个线程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM