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)

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 {@Overridepublic void run() {System.out.println("Doing heavy processing - START "+Thread.currentThread().getName());try {Thread.sleep(1000);//Get database connection, delete unused data from DBdoDBProcessing();} 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);}@Overridepublic void run() {System.out.println("MyThread - START "+Thread.currentThread().getName());try {Thread.sleep(1000);//Get database connection, delete unused data from DBdoDBProcessing();} 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多线程示例

java多线程示例_Java线程示例相关推荐

  1. java多线程抽奖_java 线程池、多线程并发实战(生产者消费者模型 1 vs 10) 附案例源码...

    导读 前二天写了一篇<Java 多线程并发编程>点我直达,放国庆,在家闲着没事,继续写剩下的东西,开干! 线程池 为什么要使用线程池 例如web服务器.数据库服务器.文件服务器或邮件服务器 ...

  2. java多线程基础_java线程基础

    1. 创建线程的两种方式 2. 线程的生命周期 3. 同步的方式 4. 死锁 5. 生产消费模型.监控模型 创建线程的两种方式 Java代码   publicclassThread1extendsTh ...

  3. java多线程构造函数_java线程基础巩固---多线程与JVM内存结构的关系及Thread构造函数StackSize的理解...

    多线程与JVM内存结构的关系[了解]: 对于最后一个有疑问的构造中stackSize参数,其实学过编程滴人从参数字面就比较容易理解,栈大小嘛,这里从官方文档上来了解一下这个参数: 而之前在学习java ...

  4. java多线程 门闩_Java线程与并发编程实践----同步器(倒计时门闩,同步屏障)...

    Java提供的synchronized关键字对临界区进行线程同步访问.由于基于synchronized很难 正确编写同步代码,并发工具类提供了高级的同步器.倒计时门闩(countdown latch) ...

  5. Java多线程系列--“JUC线程池”06之 Callable和Future

    转载自  Java多线程系列--"JUC线程池"06之 Callable和Future Callable 和 Future 简介 Callable 和 Future 是比较有趣的一 ...

  6. Java多线程之守护线程实战

    转载自 Java多线程之<<守护线程>>实战 定义 什么是守护线程?与守护线程相对应的就是用户线程,守护线程就是守护用户线程,当用户线程全部执行完结束之后,守护线程才会跟着结束 ...

  7. java多线程通信_Java多线程-线程通信

    原标题:Java多线程-线程通信 通信的方式 要想实现多个线程之间的协同,如:线程执行先后顺序.获取某个线程执行的结果等等.涉及到线程之间的相互通信,分为下面四类: 文件共享 网络共享 共享变量 JD ...

  8. java线程池多线程优先级_Java线程优先级

    java线程池多线程优先级 Priority of a thread describes how early it gets execution and selected by the thread ...

  9. java语音验证码_Java代码示例_Java语音验证接口 | 微米-中国领先的短信彩信接口平台服务商...

    Java语音验证接口代码示例 请求 import java.util.HashMap; import java.util.Map; public class IvrDemo { /** * 语音验证接 ...

最新文章

  1. R语言使用WVPlots包可视化收入与年龄的Hexbin图并叠加平滑曲线实战
  2. 使用容器和数据库克隆进行数据库迁移
  3. Zookeeper分布式一致性原理(一):分布式架构
  4. sendmail邮件服务器的基本建立过程
  5. 大佬对大佬,史诗级面试现场!!!
  6. 完整且易读的微信小程序的注册页面(包含倒计时验证码、获取用户信息)
  7. tftp命令linux,tftp命令使用详解
  8. 【工作周报】2019年7月 前端开发工作周报汇总
  9. window10官方工具在线升级失败,终极解决方案
  10. SQLMAP使用教程(一)
  11. Xshell “所选的用户密钥未在远程主机上注册,请再试一次”SSH 登录远程linux服务器(良心整理)
  12. steam账号连接服务器遇到问题,无法预料的服务器浏览器反应 - Steam Support
  13. 定制linux 安装光盘
  14. 【Linux学习笔记】20:Bash基础-历史命令
  15. Api 数据自动入库
  16. c语言考研面试经常问到的问题,考研复试常见问题(C/C++、Java)
  17. 比尔盖茨的15个预言,如今全已成真
  18. 微信公众号还会有二次繁荣吗?
  19. 迷宫寻宝(BFS模板题)
  20. Windows10设置任务栏透明化

热门文章

  1. 学习可以借鉴的大牛们的网站
  2. ajax内调用WCF服务
  3. Okio 1.9简单入门
  4. 强大的SqlCacheDependency【转】
  5. [转载] boost python numpy_boost.python 与 boost.numpy安装的一些注意事项
  6. [转载] Java——System.exit()用法及个人理解
  7. day31(GIL锁)
  8. 并发教程--JAVA5中 计数信号量(Counting Semaphore)例子
  9. What's new in C# from 2.0 to 5.0
  10. html与css基础教程:CSS构造块