浅谈Java的多线程机制
- 格式:pdf
- 大小:143.57 KB
- 文档页数:2
java多线程模拟pos共识机制各位编程爱好者们!今天咱们要来一起探索一个超级有趣的话题——用Java多线程模拟PoS(权益证明)共识机制。
这就好比是在数字世界里组织一场独特的“财富投票”大会,每个参与者都根据自己的“财富”(权益)来争取发言权和决策权。
那咱们就赶紧开始这场奇妙的旅程吧!咱们得搞清楚啥是PoS共识机制。
想象一下,在一个区块链的世界里,大家都想参与记账,但是谁来记呢?PoS就像是一场根据你拥有的“财产”多少来决定谁有资格记账的游戏。
拥有的财产越多,也就是权益越大,那么获得记账权的机会就越高。
就好比在一个公司里,股份越多的股东,在决策的时候就越有话语权一样。
接下来,咱们用Java多线程来模拟这个过程。
多线程就像是一群勤劳的小蜜蜂,它们可以同时干活,让咱们的程序更高效地运行。
在这个模拟中,每个线程就代表一个节点,也就是参与这场“财富投票”的选手。
咱们先创建一个节点类,这个类里面有一些属性,比如节点的权益值,也就是它的“财富”。
然后,每个节点都要去竞争记账权。
怎么竞争呢?这就像是抽奖一样,不过这个抽奖不是完全随机的,而是根据节点的权益值来决定中奖概率。
权益值越高,中奖的可能性就越大。
在Java代码里,咱们可以通过一个随机数生成器来模拟这个抽奖过程。
比如说,我们给每个节点分配一个随机数范围,这个范围的大小就和它的权益值成正比。
然后,生成一个随机数,看看这个随机数落在哪个节点的范围内,那个节点就获得了记账权。
但是,这还没完哦!为了让这个模拟更加真实,咱们还得考虑到一些其他的因素。
比如说,节点可能会因为网络延迟或者其他原因暂时无法参与竞争。
这时候,咱们就可以用线程的休眠来模拟这种情况。
当一个节点休眠的时候,它就暂时退出了这场“财富投票”,等它苏醒过来,再重新加入竞争。
另外,咱们还得记录每个节点获得记账权的次数,这样就能看出不同权益值的节点在竞争中的表现啦。
就像是在比赛中记录每个选手的得分一样,最后看看谁是这场“财富投票”大赛的冠军。
JAVA多线程的使用场景与注意事项总结Java多线程是指在一个程序中同时运行多个线程,每个线程都有自己的执行代码,但是又共享同一片内存空间和其他系统资源。
多线程的使用场景和注意事项是我们在开发中需要关注的重点,下面将详细进行总结。
一、Java多线程的使用场景:1.提高程序的执行效率:多线程可以充分利用系统资源,将一些耗时的操作放到一个线程中执行,避免阻塞主线程,提高程序的执行效率。
2.实现并行计算:多线程可以将任务拆分成多个子任务,每个子任务分配给一个线程来执行,从而实现并行计算,提高计算速度。
3.响应性能提升:多线程可以提高程序的响应性能,比如在用户界面的开发中,可以使用多线程来处理用户的输入和操作,保证界面的流畅性和及时响应。
4.实时性要求高:多线程可以实现实时性要求高的任务,比如监控系统、实时数据处理等。
5.任务调度与资源管理:多线程可以实现任务的调度和资源的管理,通过线程池可以更好地掌控任务的执行情况和使用系统资源。
二、Java多线程的注意事项:1.线程安全性:多线程操作共享资源时,要注意线程安全问题。
可以通过使用锁、同步方法、同步块等方式来解决线程安全问题。
2.死锁:多线程中存在死锁问题,即多个线程相互等待对方释放资源,导致程序无法继续执行。
要避免死锁问题,应尽量减少同步块的嵌套和锁的使用。
3.内存泄漏:多线程中存在内存泄漏问题,即线程结束后,线程的资源没有得到释放,导致内存占用过高。
要避免内存泄漏问题,应及时释放线程资源。
4.上下文切换:多线程的切换会带来上下文切换的开销,影响程序的执行效率。
要注意合理分配线程的数量,避免过多线程的切换。
5. 线程同步与通信:多线程之间需要进行同步和通信,以保证线程之间的正确协调和数据的一致性。
可以使用synchronized关键字、wait(和notify(方法等方式进行线程同步和通信。
6.线程池的使用:在多线程编程中,可以使用线程池来管理线程的创建和销毁,可以减少线程的创建和销毁的开销,提高程序的性能。
java多线程:Java 线程简介疯狂代码 / ĵ:http://Java/Article23914.html、本教程有什么内容? 本教程研究了线程的基础知识 ― 线程是什么、线程为什么有用以及怎么开始编写使用线程的简单程序。
我们还将研究更复杂的、使用线程的应用程序的基本构件 ― 如何在线程之间交换数据、如何控制线程以及线程如何互相通信。
2、我应该学习这个教程吗? 本教程适用于拥有丰富 Java 语言应用知识,但又没有多少多线程或并发性经验的 Java 程序员。
学习完本教程之后,您应该可以编写一个使用线程的简单程序。
您还应该可以阅读并理解以简单方法使用线程的程序。
II、线程基础 1、什么是线程? 几乎每种操作系统都支持进程的概念 ―― 进程就是在某种程度上相互隔离的、独立运行的程序。
线程化是允许多个活动共存于一个进程中的工具。
大多数现代的操作系统都支持线程,而且线程的概念以各种形式已存在了好多年。
Java 是第一个在语言本身中显式地包含线程的主流编程语言,它没有把线程化看作是底层操作系统的工具。
有时候,线程也称作轻量级进程。
就象进程一样,线程在程序中是独立的、并发的执行路径,每个线程有它自己的堆栈、自己的程序计数器和自己的局部变量。
但是,与分隔的进程相比,进程中的线程之间的隔离程度要小。
它们共享内存、文件句柄和其它每个进程应有的状态。
进程可以支持多个线程,它们看似同时执行,但互相之间并不同步。
一个进程中的多个线程共享相同的内存地址空间,这就意味着它们可以访问相同的变量和对象,而且它们从同一堆中分配对象。
尽管这让线程之间共享信息变得更容易,但您必须小心,确保它们不会妨碍同一进程里的其它线程。
Java 线程工具和 API 看似简单。
但是,编写有效使用线程的复杂程序并不十分容易。
因为有多个线程共存在相同的内存空间中并共享相同的变量,所以您必须小心,确保您的线程不会互相干扰。
2、每个 Java 程序都使用线程 每个 Java 程序都至少有一个线程 ― 主线程。
Java多线程编程的探究刘翠焕司海峰李素朵(石家庄法商职业学院河北石家庄050091)i l一一应用科学[摘要】通过对'J ava多线稃编程的研究,得出了如何灵活、正确的使用多线程编程提高整个应用系统的性能,同时对在使用多线程编程中容易出现的问题,也做出了提示,希望能对编程者有所帮助。
【关键词】线程优先级同步阻塞中圈分类号:TP3文献标识码:^文章编号;1671--7597(2008)0510057--02线程本是操作系统的一个重要概念。
多线程是指程序中同时存在着多个执行体,他们按几条不同的执行线路共同工作,独立完成各自的功能而互不干扰。
使用多线程技术可以使系统同时运行多个执行体,减少程序的响应时间,提高计算机资源的使用效率。
正确的使用多线程技术可以提高整个应用系统的性能.而多线程机制也是Java语言的一个重要特征。
一、如何在J ava中宴现多线程在Ja va中,创建线程有两种方法:一是通过创建Thr ead二类的子类来实现,二是通过实现Runnabl e:接口的类来实现。
下面我们就这来那各种方法展开讨论。
(一)创建!Thr ead:类的子类Thr ead类最重要的方法是run0。
它为T hr ead类的方法st ar t0所调用,提供我们的线程所要执行的代码。
为了指定我们自己的代码,只需要覆盖它l我们在创建的Thr ea d类的子类中重写r un(),加入线程所要执行的代码即可。
下面是一个例子:publ i c cl as s M yT hr ead ext ends T hr e ad{St r i ng t hreadN em e:i n t se c o n d:。
i nt t i m e s:publ i c M yThr ead(St r i ng nem e,i nt x,i nt m){t hr eadN am e=nem e:s ec on d=x:t i m e s=m;publ i c voi dr un0{t r y{f or(i nt i:o:i<ti m es:i++){Sy st em out.pr int II.t hrea dN e m e):Sl ee p ICse cond):}S y st e L out.pr i nt l n(。
JAVA多线程(一)基本概念和上下文切换性能损耗1 多线程概念在理解多线程之前,我们先搞清楚什么是线程。
根据维基百科的描述,线程是操作系统能够进行运算调度的最小单位。
它被包含在进程之中,是行程中的实际运行单位。
一条线程指的是进程中一个单一顺序的控制流,一個进程中可以并行多个线程,每条线程并行执行不同的任务。
每个线程共享堆空间,拥有自己独立的栈空间。
这里反复出现的概念是线程和进程,我们在这里列出它们的区别:线程划分尺度小于进程,线程隶属于某个进程;进程是CPU、内存等资源占用的基本单位,线程是不能独立占有这些资源的;进程之间相互独立,通信比较困难,而线程之间共享一块内存区域,通信方便;进程在执行过程中,包含比较固定的入口、执行顺序和出口,而进程的这些过程会被应用程序控制。
多线程是指从软件或者硬件上实现多个线程并发执行的技术。
具有多线程能力的计算机因有硬件支持而能够在同一时间执行多个线程,进而提升整体处理效能。
2 为什么要使用多线程随着计算机硬件的发展,多核CPU已经屡见不鲜了,甚至手机处理器都早已是多核的天下。
这就给我们使用多线程提供了硬件基础,但是,只是因为硬件让我们可以实现多线程,就要这样做吗?一起来看看多线程的优点:更高的运行效率。
在多核CPU上,线程之间是互相独立的,不用互相等待,也就是所谓的“并行“。
举个例子,一个使用多线程的文件系统可以实现高吞吐量和低延迟。
这是因为我们可以用一个线程来检索存储在高速介质(例如高速缓冲存储器)中的数据,另一个线程检索低速介质(例如外部存储)中的数据,二者互不干扰,也不用等到另一个线程结束才执行;多线程是模块化的编程模型。
在单线程中,如果主执行线程在一个耗时较长的任务上卡住,或者因为网络响应问题陷入长时间等待,此时程序不会响应鼠标和键盘等操作。
多线程通过将程序分成几个功能相对独立的模块,单独分配一个线程去执行这个长耗时任务,不影响其它线程的执行,就可以避免这个问题;与进程相比,线程的创建和切换开销更小。
synchronize底层原理
Synchronize底层原理
Synchronize是Java多线程编程中最常用的一种机制,它可以用来实现线程的同步,保证多个线程同时访问某个共享资源时的安全性。
Synchronize的底层原理也就是Java内存模型,主要是控制多线程对共享变量的访问,使得多个线程能够同步执行。
Synchronize底层原理主要是基于Java内存模型来实现的,Java内存模型规定了每个线程在内存中都有一个独立的内存区域,每个线程执行时都会从自己的内存区域中取出变量,以及对变量的操作。
为了保证多个线程操作变量时的安全性,Java内存模型提供了一种机制,即线程之间的可见性,也就是当一个线程修改某个变量时,其他线程可以立即看到这个变量的修改,以确保各个线程对变量的操作都是一致的。
Synchronize实现的另一个原理就是原子性,即一个操作是不可分割的。
当多个线程同时对某个变量进行操作时,可能会导致变量的值发生改变,甚至可能出现数据不一致的情况,为了避免这种情况的发生,Synchronize会将变量的操作封装成一个原子操作,使得多线程同时操作变量时,变量的值不会出现改变。
总的来说,Synchronize的底层原理是基于Java内存模型和原子性
来实现的,它既可以保证多线程对共享变量的访问可见性,又可以保证变量操作的原子性。
因此,Synchronize可以用来实现多个线程之间的同步,保证线程安全。
java多线程学习基础篇(三)Thread类的常⽤⽅法线程Thread是⼀个程序的多个执⾏路径,执⾏调度的单位,依托于进程存在。
线程不仅可以共享进程的内存,⽽且还拥有⼀个属于⾃⼰的内存空间,这段内存空间也叫做线程栈,是在建⽴线程时由系统分配的,主要⽤来保存线程内部所使⽤的数据,如线程执⾏函数中所定义的变量。
Java中的多线程是⼀种抢占机制⽽不是分时机制。
抢占机制指的是有多个线程处于可运⾏状态,但是只允许⼀个线程在运⾏,他们通过竞争的⽅式抢占CPU。
下⾯介绍⼀些常⽤的Thread⽅法。
Thread.join():静态⽅法,返回对当前正在执⾏的线程对象的引⽤在很多情况下,主线程⽣成并起动了⼦线程,如果⼦线程⾥要进⾏⼤量的耗时的运算,主线程往往将于⼦线程之前结束,但是如果主线程处理完其他的事务后,需要⽤到⼦线程的处理结果,也就是主线程需要等待⼦线程执⾏完成之后再结束,这个时候就要⽤到join()⽅法了。
Join⽅法实现是通过wait(⼩提⽰:Object 提供的⽅法)。
当main线程调⽤t.join时候,main线程会获得线程对象t的锁(wait 意味着拿到该对象的锁),调⽤该对象的wait(等待时间),直到该对象唤醒main线程,⽐如退出后。
这就意味着main 线程调⽤t.join时,必须能够拿到线程t对象的锁。
join() ⼀共有三个重载版本,分别是⽆参、⼀个参数、两个参数:public final void join() throws InterruptedException; //⽆参数的join()等价于join(0),作⽤是⼀直等待该线程死亡public final synchronized void join(long millis) throws InterruptedException; //最多等待该线程死亡millis毫秒public final synchronized void join(long millis, int nanos) throws InterruptedException; //最多等待该线程死亡millis毫秒加nanos纳秒(1) 三个⽅法都被final修饰,⽆法被⼦类重写。
java中实现多线程的方法Java是一种非常强大的编程语言,它支持多线程,这是Java的一个重要特性。
多线程允许同时执行多个任务,从而大大提高了应用程序的效率和性能。
在Java中实现多线程的方法有很多种,下面我们将一步步地阐述这些方法。
第一种方法是继承Thread类。
我们可以在Java中创建一个继承Thread类的子类,并在子类中实现run()方法。
在run()方法中编写多线程代码。
以下是示例代码:```class MyThread extends Thread {public void run() {//多线程代码}}```在上述代码中,我们创建了一个名为MyThread的子类,并重写了Thread类的run()方法。
第二种方法是实现Runnable接口。
这种方法需要创建一个实现Runnable接口的类,然后实例化一个Thread对象并将实现Runnable 接口的类作为参数传递给Thread对象。
以下是示例代码:class MyRunnable implements Runnable {public void run() {//多线程代码}}public class Main {public static void main(String[] args) {MyRunnable obj = new MyRunnable();Thread thread = new Thread(obj);thread.start();}}```在上述代码中,我们创建了一个名为MyRunnable的类,并实现了Runnable接口。
我们在主类中创建了一个MyRunnable对象,并通过传递该对象作为参数创建了一个Thread对象。
最后启动线程。
第三种方法是使用匿名内部类。
这种方法可以减少代码的数量。
以下是示例代码:```public class Main {public static void main(String[] args) {new Thread(new Runnable() {public void run() {//多线程代码}}).start();}```在上述代码中,我们使用匿名内部类创建了一个Runnable对象并启动了一个线程。
java高级工程师面试题及答案一、Java基础知识1. 请简述Java语言的特点和优势。
Java是一种跨平台的编程语言,具有以下特点和优势:- 简单易学:Java采用C/C++风格的语法,使得开发者可以快速上手。
- 面向对象:Java是一种面向对象的语言,通过封装、继承和多态等特性,使得程序更加模块化、可复用和可维护。
- 平台无关性:Java应用程序可以在不同的操作系统平台上运行,只需编译一次即可。
- 高效性能:Java通过垃圾回收机制和即时编译器(Just-In-Time Compiler)来提高性能,同时拥有高度优化的运行时环境。
- 安全性:Java提供了安全的执行环境,通过类加载器、字节码验证和安全管理器等机制,防止恶意代码的执行。
2. 什么是Java的自动装箱和拆箱?自动装箱(Autoboxing)和拆箱(Unboxing)是Java编译器提供的便利功能。
- 自动装箱:将基本数据类型转换为对应的包装类对象,例如将int 类型转换为Integer对象。
- 自动拆箱:将包装类对象转换为基本数据类型,例如将Integer对象转换为int类型。
自动装箱和拆箱使得基本数据类型和包装类之间的转换更加方便,可以在需要包装类的地方直接使用基本数据类型,编译器会自动进行装箱或拆箱操作。
3. 请简述Java中的重载和重写的区别。
- 重载(Overload):指在同一个类中,方法名相同但参数列表不同的多个方法,可以具有不同的返回类型。
重载可以通过参数个数、类型或顺序的不同来实现。
重载的方法可以拥有不同的访问修饰符。
- 重写(Override):指在子类中重新定义父类的方法,方法名、参数列表和返回类型均相同。
重写方法不能拥有比父类更低的访问修饰符,可以拥有与父类方法相同或更宽松的异常抛出声明。
重载和重写都是多态的一种表现形式,通过编译器和虚拟机的不同处理方式来实现。
4. 请解释Java中的final关键字的作用。
Java多线程编程技巧详解Java是一种广泛使用的编程语言,而多线程编程则是Java中一个重要的开发领域。
在多线程编程中,开发者需要了解并掌握一定的技巧,以避免线程之间的冲突和死锁等问题。
本文将详细介绍Java多线程编程的常用技巧,帮助开发者轻松掌握多线程编程的精髓。
一、线程的创建与启动1. 继承Thread类创建线程:直接继承Thread类,并覆盖run()方法实现线程主体。
```public class MyThread extends Thread{public void run(){//线程执行体}}MyThread myThread = new MyThread();myThread.start();```2. 实现Runnable接口创建线程:实现Runnable接口,并在类中实例化一个Thread对象。
```public class MyRunnable implements Runnable{public void run(){//线程执行体}}MyRunnable myRunnable = new MyRunnable();Thread thread = new Thread(myRunnable);thread.start();```二、线程的处理与管理1. 同步方法:synchronized关键字用于保护共享数据不被多个线程同时访问。
```public class SynchronizedDemo implements Runnable {private int count;public synchronized void run() {for(int i = 0; i < 5; i++) {System.out.println(Thread.currentThread().getName()+":"+(count++));}}}SynchronizedDemo target = new SynchronizedDemo();Thread thread1 = new Thread(target, "A");Thread thread2 = new Thread(target, "B");thread1.start();thread2.start();```2. 锁对象:使用互斥锁对象来控制线程访问共享资源的方式。
第1篇第一部分:基础知识1. Java基本概念(1)请解释Java中的面向对象编程(OOP)的特点。
解析:面向对象编程的特点包括封装、继承和多态。
封装是指将数据和对数据的操作封装在一个类中;继承是指允许一个类继承另一个类的属性和方法;多态是指同一个方法在不同对象上表现出不同的行为。
(2)简述Java中的四种访问控制符及其作用范围。
解析:Java中的四种访问控制符分别是public、protected、默认(不写)和private。
public可以访问任何类;protected可以在同一个包内和子类中访问;默认访问(不写)只能在同一个包内访问;private只能在类内部访问。
2. Java基本数据类型(1)请列出Java中的基本数据类型,并说明其特点和取值范围。
解析:Java中的基本数据类型包括byte、short、int、long、float、double、char和boolean。
byte和short为有符号整数类型,取值范围分别为-128到127和-32,768到32,767;int为基本整型,取值范围为-2,147,483,648到2,147,483,647;long为长整型,取值范围为-9,223,372,036,854,775,808到9,223,372,036,854,775,807;float和double为浮点数类型,取值范围分别为-3.4E38到3.4E38和-1.8E308到1.8E308;char为字符类型,取值范围为0到65,535;boolean为布尔类型,取值为true或false。
(2)简述Java中的自动装箱和拆箱。
解析:自动装箱是指将基本数据类型自动转换为包装类型(如int自动转换为Integer);自动拆箱是指将包装类型自动转换为基本数据类型。
在装箱和拆箱过程中,如果数据类型不匹配,会抛出ClassCastException异常。
3. Java关键字(1)请解释Java中的关键字final、static和synchronized。
ThreadsObjective 1)Write code to define, instantiate and start new threads using bothng.Thread and ng.RunnableJava is fundamentally multi-threaded.Every thread corresponds to an instance of ng.Thread class or a sub-class.A thread becomes eligible to run, when its start() method is called. Thread schedulerco-ordinates between the threads and allows them to run.When a thread begins execution, the scheduler calls its run method.Signature of run method–public void run()When a thread returns from its run method (or stop method is called –deprecated in1.2), its dead. It cannot be restarted, but its methods can be called. (it ’s jusno more in a running state)If start is called again on a dead thread, IllegalThreadStateException is thrown.When a thread is in running state, it may move out of that state for various reasons.When it becomes eligible for execution again, thread scheduler allows it to run.There are two ways to implement threads.1. Extend Thread classpublic class Thread extendsObject implements RunnableThread()Thread(Runnable target)Thread(Runnable targe, String name)Thread(String name)Thread(ThreadGroup group, Runnable target)Thread(ThreadGroup group, Runnable target, String name)Thread(ThreadGroup group, String name)Create a new class, extending the Thread class.Provide a public void run method, otherwise empty run in Thread class will beexecuted.Create an instance of the new class.Call start method on the instance (don ’c tall run –it will be executed on the samethread)2. Implement Runnable interfacepublic interface Runnableonly one method: public void runCreate a new class implementing the Runnable interface.Provide a public void run method. Create an instance ofthis class.Create a Thread, passing the instance as a targ–e n t ew Thread(object)Target should implement Runnable, Thread class implements it, so it can be a targetitself.Call the start method on the Thread.JVM creates one user thread for running a program. This thread is called main thread.The main method of the class is called from the main thread. It dies when the mainmethod ends. If other user threads have been spawned from the main thread, programkeeps running even if main thread dies. Basically a program runs until all the userthreads (non-daemon threads) are dead.A thread can be designated as a daemon thread by calling setDaemon(boolean)method. This method should be called before the thread is started, otherwiseIllegalThreadStateException will be thrown.A thread spawned by a daemon thread is a daemon thread.Threads have priorities. Thread class have constants MAX_PRIORITY (10),MIN_PRIORITY (1), NORM_PRIORITY (5)A newly created thread gets its priority from the creating thread. Normally it ’NORM_PRIORITY.getPriority and setPriority are the methods to deal with priority of threads.Java leaves the implementation of thread scheduling to JVM developers. Two typesof scheduling can be done.1. Pre-emptive Scheduling.Ways for a thread to leave running state -It can cease to be ready to execute ( by calling a blocking i/o method)It can get pre-empted by a high-priority thread, which becomes ready to execute.It can explicitly call a thread-scheduling method such as wait or suspend.Solaris JVM ’s a re-epm r ep ti v e.Windows JVM’s were pr-eemptive until Java 1.0.22. Time-sliced or Round Robin SchedulingA thread is only allowed to execute for a certain amount of time. After that, it has tocontend for the CPU (virtual CPU, JVM) time with other threads.This prevents a high-priority thread mono-policing the CPU.The drawback with this scheduling is–it creates a non-deterministic system–at anypoint in time, you cannot tell which thread is running and how long it may continue torun.Mactinosh JVM ’sWindows JVM’s after Java 1.0.2Of the two methods of creating a new thread the use of Runnable is probably morecommon. The other method for creating a thread is to create a class that is descendedfrom Thread. This is easy to do but it means you cannot inherit from any other class,Objective 2)Recognize conditions that might prevent a thread from executing.Different states of a thread:1. YieldingYield is a public static void method. Operates on current thread. For static method,call Thread.yield() is ok, don ’t need call t.yield(), where t is instance of Thread, but compiler will pass it.Moves the thread from running to ready state.If there are no threads in ready state, the yielded thread may continue execution,otherwise it may have to compete with the other threads to run.Run the threads that are doing time-consuming operations with a low priority and callyield periodically from those threads to avoid those threads locking up the CPU.2. SleepingSleep is also a public static void method.Sleeps for a certain amount of time. (passing time without doing anything and w/ousing CPU)Two overloaded versions–one with milliseconds, one with milliseconds andnanoseconds.Throws an InterruptedException.(must be caught)After the time expires, the sleeping thread goes to ready state. It may not executeimmediately after the time expires. If there are other threads in ready state, it mayhave to compete with those threads to run. The correct statement is the sleepingthread would executesome time afterthe specified time period has elapsed.If interrupt method is invoked on a sleeping thread, the thread moves to ready state.The next time it begins running, it executes the InterruptedException handler.3. SuspendingSuspend and resume are instance methods and are deprecated in 1.2A thread that receives a suspend call, goes to suspended state and stays there until itreceives a resume call on it.A thread can suspend it itself, or another thread can suspend it.But, a thread can be resumed only by another thread.Calling resume on a thread that is not suspended has no effect.Compiler won ’t warn you if suspend and resume are s s u s c i v c e statements, althoughthe thread may not be able to be restarted.4. BlockingMethods that are performing I/O have to wait for some occurrence in the outsideworld to happen before they can proceed. This behavior is blocking.If a method needs to wait an indeterminable amount of time until some I/O takesplace, then the thread should graciously step out of the CPU. All Java I/O methodsbehave this way.A thread can also become blocked, if it failed to acquire the lock of a monitor.5. Waitingwait, notify and notifyAll methods are not called on Thread, they ’re called on Object.Because the object is the one which controls the threads in this case. It asks thethreads to wait and then notifies when its state changes. It ’s called a monitor.Wait puts an executing thread into waiting state.(to the monitor ’s waiting pool) Notify moves one thread in the monitor ’s waiting pool to ready state. We cannotcontrol which thread is being notified. notifyAll is recommended. NotifyAll moves all threads in the monitor aiting po’o l stowready.These methods can only be called from synchronized code, or anIllegalMonitorStateException will be thrown. In other words, only the threads thatobtained the object ’s lock can call these methods.The sleepmethod is static and pauses execution for a set number of milliseconds. Thereis a version that is supposed to pause for a set number of nanoseconds, Here is anexample of putting a Thread to sleep, note how the sleep method throws InterruptedException.public class TSleep extendsThread{ public static voidmain(String argv[]){TSleep t = new TSleep();t.start();}public void run(){try{while(true){this.sleep(1000);System.out.println("loopingwhile");}}catch(InterruptedExceptionie){} }}Objective 3)Write code using synchronized wait notify and notifyAll to protectagainst concurrent access problems and to communicate betweenthreads. Define the interaction between threads and between threadsand object locks when executing synchronized wait notify or notifyAll.Locks, Monitors and SynchronizationEvery object has a lock (for every synchronized code block). At any moment, thislock is controlled by at most one thread.A thread that wants to execute an object ’s synchronized code must acquire the lock ofthe object. If it cannot acquire the lock, the thread goes into blocked state and comesto ready only when the object ’s lock is available.When a thread, which owns a lock, finishes executing the synchronized code, it givesup the lock.Monitor is an object that can block and revive threads, an object that controls clientthreads. Asks the client threads to wait and notifies them when the time is right tocontinue, based on its state. In strict Java terminology, any object that has somesynchronized code is a monitor.2 ways to synchronize:1. Synchronize the entire methodDeclare the method to be synchronized - very common practice.Thread should obtain the o b e j ct ’s lock.2. Synchronize part of the methodHave to pass an arbitrary object which lock is to be obtained to execute thesynchronized code block (part of a method).Synchronized(target) {statements}We can specify “this ” in place object, to obtain v f e l o r y c k b i n r i g e – not verycommonIf target is null, then the NullPointerException is thrown.wait – points to remembercalling thread gives up CPUcalling thread gives up the lockcalling thread goes to monitor ’s waiting poolwait also has a version with timeout in milliseconds. Use this if you ’re not surewhen the current thread will get notified, this avoids the thread being stuck in waitstate forever.notify – points to rememberone thread gets moved out of monitor ’s waiting pool to ready statenotifyAll moves all the threads to ready stateThread gets to execute must re-acquire the lock of the monitor before it canproceed.Note the differences between blocked and waiting.BlockedWaiting Thread is waiting to get a lock on the Thread has been asked to wait. (by meansmonitor. of wait method)(or waiting for a blocking i/o method)Caused by the thread tried to execut e some synchronized code. (or a blocking The thread already acquired the lock andexecuted some synchronized code beforei/o method) coming across a wait call.Can move to ready only when the lock is available. ( or the i/o operation is complete)Can move to ready only when it gets notified (by means of notify or notifyAll) Points for complex models:1. Always check monitor ’s state in a w h o i p le , rloather than in an if statement. 2. Always call notifyAll, instead of notify.wait and sleep must be enclosed in a try/catch for InterruptedException.A single thread can obtain multiple locks on multiple objects (or on the same object)A thread owning the lock of an object can call other synchronous methods on thesame object. (this is another lock) Other threads can ’t do that. They should wait to ge the lock.Non-synchronous methods can be called at any time by any thread.Synchronous methods are re-entrant. So they can be called recursively.Synchronized methods can be overrided to be non-synchronous.synchronizedbehavior affects only the original class.Locks on inner/outer objects are independent. Getting a lock on outer object doesnmean getting the lock on an inner object as well, that lock should be obtainedseparately.Locks on static synchronized method called Class wide lock. The class wide lockand the instance lock being independent of each other.wait and notify should be called from synchronized code. This ensures that whilecalling these methods the thread always has the lock on the object. If you havewait/notify in non- synchronized code compiler won ’t catch this. At runtime,if thethread doesn ’t have the lock while calling these m s e,t h a o n dIllegalMonitorStateException is thrown.Deadlocks can occur easily. e.g, Thread A locked Object A and waiting to get a lockon Object B, but Thread B locked Object B and waiting to get a lock on Object A.They’ll be in this state forever.It ’s the programmer ’s responsibility to avoid the d. e A a l d w l a o y c s k get the locks in thesame order.While ‘suspended’, the thread keeps the locks it o b ta sio ne sdu sp en d is depr–ecated in1.2Use of stop is also deprecated, instead use a flag in run method. Com pilweron’t warnyou, if you have statements after a call to stop, even though they are not reachable.A typical example of using the wait/notify protocol to allow communication betweenThreads appears to involve apparently endless loops such as//producing codewhile(true){try{wait();}catch (InterruptedException e) {} }//some producing action goes herenotifyAll();Conditions that might prevent a thread from executing :The thread is not the highest priority thread and so cannot get CPU time.The thread is waiting on a condition because someone invoked wait() for the thread.The thread has explicitly yielded control by invoking yield() to allow another threadof the same priority to run.The thread has been put to sleep using the sleep() methodSomeone has suspended the thread using the suspend() method. (deprecated in Java 2)It is blocked for file I/OThere is more than one thread with the same highest priority and JVM is switching between these threads, at the moment, the thread in question is awaiting CPU time.。