java多线程示例_Java线程示例

java多线程示例

Welcome to the Java Thread Example. Process and Thread are two basic units of execution. Concurrency programming is more concerned with java threads.

欢迎使用Java线程示例。 进程线程是执行的两个基本单元。 并发编程更关注Java线程。

处理 (Process)

A process is a self contained execution environment and it can be seen as a program or application. However a program itself contains multiple processes inside it. Java runtime environment runs as a single process which contains different classes and programs as processes.

流程是一个独立的执行环境,可以将其视为程序或应用程序。 但是,程序本身内部包含多个进程。 Java运行时环境作为单个进程运行,其中包含不同的类和程序作为进程。

线 (Thread)

Thread can be called lightweight process. Thread requires less resources to create and exists in the process, thread shares the process resources.

线程可以称为轻量级进程 。 线程需要较少的资源来创建和存在于进程中,线程共享进程资源。

Java线程示例 (Java Thread Example)

java thread example

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线程,我们可以从中创建多个线程。

Multithreading refers to two or more threads executing concurrently in a single program. A computer single core processor can execute only one thread at a time and time slicing is the OS feature to share processor time between different processes and threads.

多线程是指在单个程序中同时执行的两个或多个线程。 一种计算机单核处理器可以一次仅执行一个线程和时间分片是OS特征不同的进程和线程之间共享处理器时间。

Java线程的好处 (Java Thread Benefits)

  1. Java Threads are lightweight compared to processes, it takes less time and resource to create a thread.

    与进程相比,Java线程轻巧,创建线程所需的时间和资源更少。
  2. Threads share their parent process data and code

    线程共享其父流程数据和代码
  3. Context switching between threads is usually less expensive than between processes.

    在线程之间进行上下文切换通常比在进程之间便宜。
  4. Thread intercommunication is relatively easy than process communication.

    线程相互通信比过程通信相对容易。

Java provides two ways to create a thread programmatically.

Java提供了两种方法以编程方式创建线程。

  1. Implementing the java.lang.Runnable interface.

    实现java.lang.Runnable接口。
  2. Extending the java.lang.Thread class.

    扩展java.lang.Thread类。

Java线程示例–实现Runnable接口 (Java Thread Example – implementing Runnable interface)

To make a class runnable, we can implement java.lang.Runnable interface and provide implementation in public void run() method. To use this class as Thread, we need to create a Thread object by passing object of this runnable class and then call start() method to execute the run() method in a separate thread.

为了使一个类可运行,我们可以实现java.lang.Runnable接口,并在public void run()方法中提供实现。 要将此类用作Thread,我们需要通过传递此runnable类的对象来创建Thread对象,然后调用start() run()方法在单独的线程中执行run()方法。

Here is a java thread example by implementing Runnable interface.

这是通过实现Runnable接口的Java线程示例。

package com.journaldev.threads;

public class HeavyWorkRunnable implements Runnable {

    @Override
    public void run() {
        System.out.println("Doing heavy processing - START "+Thread.currentThread().getName());
        try {
            Thread.sleep(1000);
            //Get database connection, delete unused data from DB
            doDBProcessing();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Doing heavy processing - END "+Thread.currentThread().getName());
    }

    private void doDBProcessing() throws InterruptedException {
        Thread.sleep(5000);
    }

}

Java线程示例–扩展线程类 (Java Thread Example – extending Thread class)

We can extend java.lang.Thread class to create our own java thread class and override run() method. Then we can create it’s object and call start() method to execute our custom java thread class run method.

我们可以扩展java.lang.Thread类来创建我们自己的java线程类并重写run()方法。 然后,我们可以创建它的对象并调用start()方法以执行我们的自定义Java线程类run方法。

Here is a simple java thread example showing how to extend Thread class.

这是一个简单的Java线程示例,显示了如何扩展Thread类。

package com.journaldev.threads;

public class MyThread extends Thread {

    public MyThread(String name) {
        super(name);
    }

    @Override
    public void run() {
        System.out.println("MyThread - START "+Thread.currentThread().getName());
        try {
            Thread.sleep(1000);
            //Get database connection, delete unused data from DB
            doDBProcessing();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("MyThread - END "+Thread.currentThread().getName());
    }

    private void doDBProcessing() throws InterruptedException {
        Thread.sleep(5000);
    }
    
}

Here is a test program showing how to create a java thread and execute it.

这是一个测试程序,显示了如何创建Java线程并执行它。

package com.journaldev.threads;

public class ThreadRunExample {

    public static void main(String[] args){
        Thread t1 = new Thread(new HeavyWorkRunnable(), "t1");
        Thread t2 = new Thread(new HeavyWorkRunnable(), "t2");
        System.out.println("Starting Runnable threads");
        t1.start();
        t2.start();
        System.out.println("Runnable Threads has been started");
        Thread t3 = new MyThread("t3");
        Thread t4 = new MyThread("t4");
        System.out.println("Starting MyThreads");
        t3.start();
        t4.start();
        System.out.println("MyThreads has been started");
        
    }
}

Output of the above java thread example program is:

上面的java线程示例程序的输出是:

Starting Runnable threads
Runnable Threads has been started
Doing heavy processing - START t1
Doing heavy processing - START t2
Starting MyThreads
MyThread - START Thread-0
MyThreads has been started
MyThread - START Thread-1
Doing heavy processing - END t2
MyThread - END Thread-1
MyThread - END Thread-0
Doing heavy processing - END t1

Once we start any thread, it’s execution depends on the OS implementation of time slicing and we can’t control their execution. However we can set threads priority but even then it doesn’t guarantee that higher priority thread will be executed first.

一旦启动任何线程,它的执行就取决于时间片的OS实现,我们无法控制它们的执行。 但是,我们可以设置线程优先级,但是即使那样也不能保证优先级更高的线程将首先执行。

Run the above program multiple times and you will see that there is no pattern of threads start and end.

多次运行上面的程序,您将看到没有开始和结束线程的模式。

可运行与线程 (Runnable vs Thread)

If your class provides more functionality rather than just running as Thread, you should implement Runnable interface to provide a way to run it as Thread. If your class only goal is to run as Thread, you can extend Thread class.

如果您的类提供了更多功能,而不仅仅是作为线程运行,则应实现Runnable接口,以提供一种将其作为线程运行的方法。 如果您的类的唯一目标是作为Thread运行,则可以扩展Thread类。

Implementing Runnable is preferred because java supports implementing multiple interfaces. If you extend Thread class, you can’t extend any other classes.

首选实现Runnable,因为Java支持实现多个接口。 如果扩展Thread类,则不能扩展任何其他类。

Tip: As you have noticed that thread doesn’t return any value but what if we want our thread to do some processing and then return the result to our client program, check our Java Callable Future.

提示 :正如您已经注意到的那样,线程不返回任何值,但是如果我们希望我们的线程进行一些处理然后将结果返回给客户端程序,请检查Java Callable Future

Update: From Java 8 onwards, Runnable is a functional interface and we can use lambda expressions to provide it’s implementation rather than using anonymous class. For more details, check out Java 8 Functional Interfaces.

更新 :从Java 8开始,Runnable是一个功能接口,我们可以使用lambda表达式提供其实现,而不是使用匿名类。 有关更多详细信息,请查看Java 8 Functional Interfaces

翻译自: https://www.journaldev.com/1016/java-thread-example

java多线程示例

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值