在讨论多线程之前,让我们先讨论线程。线程是进程中轻量级的最小部分,可以与同一进程的其他部分(其他线程)并发运行。线程是独立的,因为它们都有独立的执行路径,这就是为什么如果一个线程中发生异常,它不会影响其他线程的执行。进程的所有线程共享公共内存。同时执行多个线程的过程称为多线程。

让我们把讨论总结成以下几点:

1. 多线程的主要目的是同时执行程序的两个或多个部分,以最大限度地利用CPU时间。多线程程序包含两个或多个可以并发运行的部分。程序的每个这样的部分称为线程。

2. 线程是轻量级子进程,它们共享公共内存空间。在多线程环境中,受益于多线程的程序可以利用最大的CPU时间,使空闲时间保持在最小。

3.线程可以处于以下状态之一:

新-尚未启动的线程处于此状态。

RUNNABLE——在Java虚拟机中执行的线程处于这种状态。

阻塞——等待监视器锁的阻塞线程处于这种状态。

等待——正在无限期等待另一个线程执行特定操作的线程处于这种状态。

TIMED_WAITING—等待另一个线程执行某个操作长达指定等待时间的线程处于这种状态。

终止-已退出的线程处于此状态。

在给定的时间点上,线程只能处于一种状态。

多任务vs多线程vs多处理vs并行处理

如果您是java新手,您可能会对这些术语感到困惑,因为在我们讨论多线程时它们经常使用。让我们简单地谈一谈。

多任务处理: 同时执行多个任务的能力称为多任务处理。

多线程: 我们已经讨论过了。它是一个同时执行多个线程的进程。多线程也称为基于线程的多任务处理。

多处理: 它与多任务处理相同,但是在多处理中涉及多个cpu。另一方面,一个CPU参与多任务处理。

并行处理: 它是指在一个计算机系统中使用多个cpu。

在用Java创建线程

在Java中有两种创建线程的方法:

1)通过扩展Thread类。

2)通过实现Runnable接口。

在开始创建线程的程序(代码)之前,让我们先看看Thread类的这些方法。在下面的示例中,我们很少使用这些方法。

getName():用于获取线程的名称

getPriority():获取线程的优先级

isAlive():确定线程是否仍在运行

join():等待线程终止

run():线程的入口点

sleep():挂起线程一段时间

start():通过调用线程的run()方法来启动线程

方法1:通过扩展线程类创建线程Example 1:

class MultithreadingDemo extends Thread{

public void run(){

System.out.println("My thread is in running state.");

}

public static void main(String args[]){

MultithreadingDemo obj=new MultithreadingDemo();

obj.start();

} }

Output:

My thread is in running state.

Example 2:

class Count extends Thread{

Count()

{

super("my extending thread");

System.out.println("my thread created" + this);

start();

}

public void run()

{

try

{

for (int i=0 ;i<10;i++)

{

System.out.println("Printing the count " + i);

Thread.sleep(1000);

}

}

catch(InterruptedException e)

{

System.out.println("my thread interrupted");

}

System.out.println("My thread run is over" );

}}class ExtendingExample{

public static void main(String args[])

{

Count cnt = new Count();

try

{

while(cnt.isAlive())

{

System.out.println("Main thread will be alive till the child thread is live");

Thread.sleep(1500);

}

}

catch(InterruptedException e)

{

System.out.println("Main thread interrupted");

}

System.out.println("Main thread's run is over" );

}}

输出:

my thread createdThread[my runnable thread,5,main]Main thread will be alive till the child thread is livePrinting the count 0Printing the count 1Main thread will be alive till the child thread is livePrinting the count 2Main thread will be alive till the child thread is livePrinting the count 3Printing the count 4Main thread will be alive till the child thread is livePrinting the count 5Main thread will be alive till the child thread is livePrinting the count 6Printing the count 7Main thread will be alive till the child thread is livePrinting the count 8Main thread will be alive till the child thread is livePrinting the count 9mythread run is overMain thread run is over

方法2:通过实现Runnable接口创建线程

一个简单示例

class MultithreadingDemo implements Runnable{

public void run(){

System.out.println("My thread is in running state.");

}

public static void main(String args[]){

MultithreadingDemo obj=new MultithreadingDemo();

Thread tobj =new Thread(obj);

tobj.start(); } }

输出:

My thread is in running state.

示例程序2:

观察这个程序的输出,并尝试理解这个程序中发生了什么。如果您已经理解了每个线程方法的用法,那么您应该不会遇到任何问题,请理解这个示例。

class Count implements Runnable{

Thread mythread ;

Count()

{

mythread = new Thread(this, "my runnable thread");

System.out.println("my thread created" + mythread);

mythread.start();

}

public void run()

{

try

{

for (int i=0 ;i<10;i++)

{

System.out.println("Printing the count " + i);

Thread.sleep(1000);

}

}

catch(InterruptedException e)

{

System.out.println("my thread interrupted");

}

System.out.println("mythread run is over" );

}}class RunnableExample{

public static void main(String args[])

{

Count cnt = new Count();

try

{

while(cnt.mythread.isAlive())

{

System.out.println("Main thread will be alive till the child thread is live");

Thread.sleep(1500);

}

}

catch(InterruptedException e)

{

System.out.println("Main thread interrupted");

}

System.out.println("Main thread run is over" );

}}

输出:

my thread createdThread[my runnable thread,5,main]Main thread will be alive till the child thread is livePrinting the count 0Printing the count 1Main thread will be alive till the child thread is livePrinting the count 2Main thread will be alive till the child thread is livePrinting the count 3Printing the count 4Main thread will be alive till the child thread is livePrinting the count 5Main thread will be alive till the child thread is livePrinting the count 6Printing the count 7Main thread will be alive till the child thread is livePrinting the count 8Main thread will be alive till the child thread is livePrinting the count 9mythread run is overMain thread run is over

线程优先级

线程优先级是决定一个线程如何对待其他线程的整数。

线程优先级决定何时从一个正在运行的线程切换到另一个线程,进程称为上下文切换

线程可以自动释放控制,准备运行的最高优先级线程是给定CPU的。

一个线程可以被一个高优先级线程抢占,不管低优先级线程在做什么。当高优先级线程想要运行时,它就会运行。

要设置线程的优先级,使用setPriority()方法,它是线程类的一个方法。

我们可以使用MIN_PRIORITY、NORM_PRIORITY或MAX_PRIORITY来代替在整数中定义优先级。

方法: isAlive() 和 join()

在所有实际情况下,主线程应该是最后一个完成,其他从主线程派生的线程也会完成。

要知道线程是否已经完成,我们可以在线程上调用isAlive(),如果线程没有完成,它将返回true。

另一种方法是使用join()方法,当从父线程调用该方法时,该方法使父线程等待子线程终止。

这些方法是在Thread类中定义的。

在上面的例子中,我们也使用了isAlive()方法。

同步

多线程为程序引入了异步行为。如果一个线程正在写一些数据,那么另一个线程可能正在读取相同的数据。这可能会带来不一致。

当两个或多个线程需要访问共享资源时,应该以某种方式让资源一次只被一个资源使用。实现这一点的过程称为同步。

要实现同步行为,java有同步方法。一旦线程位于同步方法中,其他线程就不能调用同一对象上的任何其他同步方法。然后所有其他线程等待第一个线程从同步块中出来。

当我们想要同步对一个不是为多线程访问而设计的类的对象的访问时,并且需要同步访问的方法的代码对我们不可用,在这种情况下,我们不能将synchronized添加到适当的方法中。在java中,我们对此有解决方案,将对这个类定义的方法(需要同步)的调用以以下方式放入同步块中。

Synchronized(object){

// statement to be synchronized}

线程间通信

我们有一些java线程可以彼此通信的方法。这些方法是wait()、notify()、notifyAll()。所有这些方法只能从同步方法中调用。

1)了解同步java有一个monitor的概念。监视器可以看作是一个只能容纳一个线程的盒子。一旦一个线程进入监视器,所有其他线程必须等待该线程退出监视器。

2) wait()告诉调用线程放弃监视器并进入睡眠状态,直到其他线程进入同一监视器并调用notify()。

3) notify()唤醒同一对象上调用wait()的第一个线程。

notifyAll()唤醒同一对象上调用wait()的所有线程。优先级最高的线程将首先运行。

 为了让学习变得轻松、高效,今天给大家免费分享一套Java教学资源。帮助大家在成为Java架构师的道路上披荆斩棘。需要资料的欢迎加入学习交流群:9285,05736

java中的多线程的示例相关推荐

  1. Java中的Volatile如何工作? Java中的volatile关键字示例

    如何在Java中使用Volatile关键字 在Java采访中,什么是volatile变量以及何时在Java中使用volatile变量是Java 采访中一个著名的多线程采访问题 . 尽管许多程序员都知道 ...

  2. Java中的多线程基本介绍

    在 Java 中,多线程是指同时执行两个或多个线程以最大限度地利用 CPU 的过程. Java 中的线程是一个轻量级进程,只需要较少的资源即可创建和共享进程资源. 多线程和多进程用于 Java 中的多 ...

  3. Java中控制多线程顺序执行

    Java中控制多线程顺序执行 一.概述 二.普通示例 三.控制示例 3.1.设置线程优先级 3.2.使用线程类的join() 3.2.1.在主线程join() 3.2.2.在子线程join() 3.3 ...

  4. Java中的多线程编程(超详细总结)

    文章目录 Java中的多线程编程(超详细总结) 一.线程与多线程的概念 二.线程与进程之间的关系 三.一个线程的生命周期 四.多线程的目的和意义 五.线程的实现的方式 Java中的多线程编程(超详细总 ...

  5. JAVA中的多线程(一)

    JAVA中的多线程(一) 进程:是一个正在执行中的程序 每一个进程执行都有一个执行的顺序,该顺序是一个执行路径,或者叫控制单元 线程:就是进程中的一个独立的控制单元 线程在控制着进程的执行 一个进程中 ...

  6. JAVA中的多线程(八):线程的优先级和yield方法

    JAVA中的多线程(八):线程的优先级和yield方法 优先级代表着抢资源的频率 所有线程默认优先级是5 yield()临时释放线程的执行权 1 class Demo implements Runna ...

  7. JAVA中的多线程与运动仿真(1)——用JAVA来放一场烟花

    JAVA中的多线程与运动仿真(1)--用JAVA来放一场烟花 一.实现效果的简单展示: 初步实现的动态效果为在鼠标点击之后,点击之处出现一簇小球,然后向不同方向散开变大. 利用这一效果,再在后续增加颜 ...

  8. 草根方式学习java中的多线程

    草根方式学习java中的多线程 下面有具体的代码和截图 源码点这里 多线程即在同一时间,可以做多件事情(说白了,就是齐头并进) 单线程就是按部就班 创建多线程有2种方式,分别是继承线程Thread类, ...

  9. java中实现多线程的三种方式

    java中实现多线程的三种方式 1.实现多线程的方法: 在java中实现多线程的两途径:继承Thread类,实现Runable接口(Callable) 2.继承Thread类实现多线程: ​ 继承类T ...

最新文章

  1. 防抖 节流_关于防抖和节流
  2. C# 写Windows服务
  3. Excessive growth of the primary database log mirror and system Performance Monitoring
  4. sql server 定时备份数据库
  5. 完全卸载ORACLE9i
  6. Oracle 该用户下所有的表
  7. 51Nod 1092 回文字符串(LCS + dp)
  8. 超全汇总,常见的芯片封装大全-道合顺大数据infinigo
  9. Win10 输入法工具栏抽风,无法调整水平垂直。
  10. 计算机在足球中的应用,人工智能在机器人足球赛中的应用
  11. python实现seo疯狂外链发送工具
  12. 新ssd硬盘怎么安装efi_如何在PC中升级和安装新的硬盘驱动器或SSD
  13. 下午:准备考试——SOA解决方案架构师认证
  14. 解决HA is not enable for this namenode错误
  15. VMware安装VMwareTolls
  16. more than and less than
  17. 2020王者营地服务器维护,至尊宝重磅返场,王者营地服务器崩溃,只因玩家等待了五年的它...
  18. 【缺陷检测】基于matlab AlexNet和SVM异常螺母检测【含Matlab源码 2147期】
  19. java基础知识复习(截取)
  20. 逻辑回归_极大似然估计

热门文章

  1. 【操作系统复习】操作系统的运行机制与体系结构
  2. java 解析 csv_在Java中将数据从CSV解析到数组
  3. npm 全局安装vuecli报错_前端脚手架CLI生成模版命令工具(包括,npm包的发布,脚手架的搭建,注意事项,优化等)...
  4. Halcon学习笔记:读取多张图片
  5. JavaSE——IO(下)(Properties类、序列化与反序列化)
  6. QT中的QTableView+QTableWidget
  7. 命令行下 pdb 调试 Python 程序
  8. 特殊构造(非捕获总结)
  9. linux 和服务通讯,Android 的Activity和Service之间的通信
  10. php代码加文件后缀,php中一行代码获取文件后缀名