在JAVA中怎么实现消息队列

在JAVA中怎么实现消息队列,第1张

java中的消息队列

消息队列是线程间通讯的手段:

import javautil

public class MsgQueue{

   private Vector queue = null;

   public MsgQueue(){

              queue = new   Vector();

   }

   public synchronized void send(Object o)

   {

      queueaddElement(o);

   }

   public synchronized Object recv()

{

     if(queuesize()==0)

        return null;

     Object o = queuefirstElement();

     queueremoveElementAt(0);//or queue[0] = null can also work

     return o;

}

}

因为java中是locked by object的所以添加synchronized 就可以用于线程同步锁定对象

可以作为多线程处理多任务的存放task的队列。他的client包括封装好的task类以及thread类

Java的多线程-线程间的通信2009-08-25 21:58

1 线程的几种状态

线程有四种状态,任何一个线程肯定处于这四种状态中的一种:

1) 产生(New):线程对象已经产生,但尚未被启动,所以无法执行。如通过new产生了一个线程对象后没对它调用start()函数之前。

2) 可执行(Runnable):每个支持多线程的系统都有一个排程器,排程器会从线程池中选择一个线程并启动它。当一个线程处于可执行状态时,表示它可能正处于线程池中等待排排程器启动它;也可能它已正在执行。如执行了一个线程对象的start()方法后,线程就处于可执行状态,但显而易见的是此时线程不一定正在执行中。

3) 死亡(Dead):当一个线程正常结束,它便处于死亡状态。如一个线程的run()函数执行完毕后线程就进入死亡状态。

4) 停滞(Blocked):当一个线程处于停滞状态时,系统排程器就会忽略它,不对它进行排程。当处于停滞状态的线程重新回到可执行状态时,它有可能重新执行。如通过对一个线程调用wait()函数后,线程就进入停滞状态,只有当两次对该线程调用notify或notifyAll后它才能两次回到可执行状态。

2 class Thread下的常用函数函数

21 suspend()、resume()

1) 通过suspend()函数,可使线程进入停滞状态。通过suspend()使线程进入停滞状态后,除非收到resume()消息,否则该线程不会变回可执行状态。

2) 当调用suspend()函数后,线程不会释放它的“锁标志”。

例11:

class TestThreadMethod extends Thread{

public static int shareVar = 0;

public TestThreadMethod(String name){

super(name);

}

public synchronized void run(){

if(shareVar==0){

for(int i=0; i<5; i++){

shareVar++;

if(shareVar==5){

thissuspend(); //(1)

}}}

else{

Systemoutprint(ThreadcurrentThread()getName());

Systemoutprintln(" shareVar = " + shareVar);

thisresume(); //(2)

}}

}

public class TestThread{

public static void main(String[] args){

TestThreadMethod t1 = new TestThreadMethod("t1");

TestThreadMethod t2 = new TestThreadMethod("t2");

t1start(); //(5)

//t1start(); //(3)

t2start(); //(4)

}}

运行结果为:

t2 shareVar = 5

i 当代码(5)的t1所产生的线程运行到代码(1)处时,该线程进入停滞状态。然后排程器从线程池中唤起代码(4)的t2所产生的线程,此时shareVar值不为0,所以执行else中的语句。

ii 也许你会问,那执行代码(2)后为什么不会使t1进入可执行状态呢?正如前面所说,t1和t2是两个不同对象的线程,而代码(1)和(2)都只对当前对象进行 *** 作,所以t1所产生的线程执行代码(1)的结果是对象t1的当前线程进入停滞状态;而t2所产生的线程执行代码(2)的结果是把对象t2中的所有处于停滞状态的线程调回到可执行状态。

iii 那现在把代码(4)注释掉,并去掉代码(3)的注释,是不是就能使t1重新回到可执行状态呢?运行结果是什么也不输出。为什么会这样呢?也许你会认为,当代码(5)所产生的线程执行到代码(1)时,它进入停滞状态;而代码(3)所产生的线程和代码(5)所产生的线程是属于同一个对象的,那么就当代码(3)所产生的线程执行到代码(2)时,就可使代码(5)所产生的线程执行回到可执行状态。但是要清楚,suspend()函数只是让当前线程进入停滞状态,但并不释放当前线程所获得的“锁标志”。所以当代码(5)所产生的线程进入停滞状态时,代码(3)所产生的线程仍不能启动,因为当前对象的“锁标志”仍被代码(5)所产生的线程占有。

#p#22 sleep()

1) sleep ()函数有一个参数,通过参数可使线程在指定的时间内进入停滞状态,当指定的时间过后,线程则自动进入可执行状态。

2) 当调用sleep ()函数后,线程不会释放它的“锁标志”。

例12:

class TestThreadMethod extends Thread{

class TestThreadMethod extends Thread{

public static int shareVar = 0;

public TestThreadMethod(String name){

super(name);

}

public synchronized void run(){

for(int i=0; i<3; i++){

Systemoutprint(ThreadcurrentThread()getName());

Systemoutprintln(" : " + i);

try{

Threadsleep(100); //(4)

}

catch(InterruptedException e){

Systemoutprintln("Interrupted");

}}}

}

public class TestThread{public static void main(String[] args){

TestThreadMethod t1 = new TestThreadMethod("t1");

TestThreadMethod t2 = new TestThreadMethod("t2");

t1start(); (1)

t1start(); (2)

//t2start(); (3)

}}

运行结果为:

t1 : 0

t1 : 1

t1 : 2

t1 : 0

t1 : 1

t1 : 2

由结果可证明,虽然在run()中执行了sleep(),但是它不会释放对象的“锁标志”,所以除非代码(1)的线程执行完run()函数并释放对象的“锁标志”,否则代码(2)的线程永远不会执行。

如果把代码(2)注释掉,并去掉代码(3)的注释,结果将变为:

t1 : 0

t2 : 0

t1 : 1

t2 : 1

t1 : 2

t2 : 2

由于t1和t2是两个对象的线程,所以当线程t1通过sleep()进入停滞时,排程器会从线程池中调用其它的可执行线程,从而t2线程被启动。

例13:

class TestThreadMethod extends Thread{

public static int shareVar = 0;

public TestThreadMethod(String name){

super(name);

}

public synchronized void run(){

for(int i=0; i<5; i++){

Systemoutprint(ThreadcurrentThread()getName());

Systemoutprintln(" : " + i);

try{

if(ThreadcurrentThread()getName()equals("t1"))

Threadsleep(200);

else

Threadsleep(100);

}

catch(InterruptedException e){

Systemoutprintln("Interrupted");

}}

}}

public class TestThread{public static void main(String[] args){

TestThreadMethod t1 = new TestThreadMethod("t1");

TestThreadMethod t2 = new TestThreadMethod("t2");

t1start();

//t1start();

t2start();

}}

运行结果为:

t1 : 0

t2 : 0

t2 : 1

t1 : 1

t2 : 2

t2 : 3

t1 : 2

t2 : 4

t1 : 3

t1 : 4

由于线程t1调用了sleep(200),而线程t2调用了sleep(100),所以线程t2处于停滞状态的时间是线程t1的一半,从从结果反映出来的就是线程t2打印两倍次线程t1才打印一次。

#p#23 yield()

1) 通过yield ()函数,可使线程进入可执行状态,排程器从可执行状态的线程中重新进行排程。所以调用了yield()的函数也有可能马上被执行。

2) 当调用yield ()函数后,线程不会释放它的“锁标志”。

例14:

class TestThreadMethod extends Thread{

public static int shareVar = 0;

public TestThreadMethod(String name){super(name);

}

public synchronized void run(){for(int i=0; i<4; i++){

Systemoutprint(ThreadcurrentThread()getName());

Systemoutprintln(" : " + i);

Threadyield();

}}

}

public class TestThread{public static void main(String[] args){

TestThreadMethod t1 = new TestThreadMethod("t1");

TestThreadMethod t2 = new TestThreadMethod("t2");

t1start();

t1start(); //(1)

//t2start(); (2)

}

}

运行结果为:

t1 : 0

t1 : 1

t1 : 2

t1 : 3

t1 : 0

t1 : 1

t1 : 2

t1 : 3

从结果可知调用yield()时并不会释放对象的“锁标志”。

如果把代码(1)注释掉,并去掉代码(2)的注释,结果为:

t1 : 0

t1 : 1

t2 : 0

t1 : 2

t2 : 1

t1 : 3

t2 : 2

t2 : 3

从结果可知,虽然t1线程调用了yield(),但它马上又被执行了。

24 sleep()和yield()的区别

1) sleep()使当前线程进入停滞状态,所以执行sleep()的线程在指定的时间内肯定不会执行;yield()只是使当前线程重新回到可执行状态,所以执行yield()的线程有可能在进入到可执行状态后马上又被执行。

2) sleep()可使优先级低的线程得到执行的机会,当然也可以让同优先级和高优先级的线程有执行的机会;yield()只能使同优先级的线程有执行的机会。

例15:

class TestThreadMethod extends Thread{

public static int shareVar = 0;

public TestThreadMethod(String name){

super(name);

}

public void run(){

for(int i=0; i<4; i++){

Systemoutprint(ThreadcurrentThread()getName());

Systemoutprintln(" : " + i);

//Threadyield(); (1)

/ (2) /

try{

Threadsleep(3000);

}

catch(InterruptedException e){

Systemoutprintln("Interrupted");

}}}

}

public class TestThread{

public static void main(String[] args){

TestThreadMethod t1 = new TestThreadMethod("t1");

TestThreadMethod t2 = new TestThreadMethod("t2");

t1setPriority(ThreadMAX_PRIORITY);

t2setPriority(ThreadMIN_PRIORITY);

t1start();

t2start();

}

}

运行结果为:

t1 : 0

t1 : 1

t2 : 0

t1 : 2

t2 : 1

t1 : 3

t2 : 2

t2 : 3

由结果可见,通过sleep()可使优先级较低的线程有执行的机会。注释掉代码(2),并去掉代码(1)的注释,结果为:

t1 : 0

t1 : 1

t1 : 2

t1 : 3

t2 : 0

t2 : 1

t2 : 2

t2 : 3

可见,调用yield(),不同优先级的线程永远不会得到执行机会。

25 join()

使调用join()的线程执行完毕后才能执行其它线程,在一定意义上,它可以实现同步的功能。

例16:

class TestThreadMethod extends Thread{

public static int shareVar = 0;

public TestThreadMethod(String name){

super(name);

}

public void run(){

for(int i=0; i<4; i++){

Systemoutprintln(" " + i);

try{

Threadsleep(3000);

}

catch(InterruptedException e){

Systemoutprintln("Interrupted");

}

}

}

}

public class TestThread{

public static void main(String[] args){

TestThreadMethod t1 = new TestThreadMethod("t1");

t1start();

try{

t1join();

}

catch(InterruptedException e){}

t1start();

}

}

运行结果为:

0

1

2

3

0

1

2

3

#p#3 class Object下常用的线程函数

wait()、notify()和notifyAll()这三个函数由javalangObject类提供,用于协调多个线程对共享数据的存取。

31 wait()、notify()和notifyAll()

1) wait()函数有两种形式:第一种形式接受一个毫秒值,用于在指定时间长度内暂停线程,使线程进入停滞状态。第二种形式为不带参数,代表waite()在notify()或notifyAll()之前会持续停滞。

2) 当对一个对象执行notify()时,会从线程等待池中移走该任意一个线程,并把它放到锁标志等待池中;当对一个对象执行notifyAll()时,会从线程等待池中移走所有该对象的所有线程,并把它们放到锁标志等待池中。

3) 当调用wait()后,线程会释放掉它所占有的“锁标志”,从而使线程所在对象中的其它synchronized数据可被别的线程使用。

例17:

下面,我们将对例11中的例子进行修改

class TestThreadMethod extends Thread{

public static int shareVar = 0;

public TestThreadMethod(String name){

super(name);

}

public synchronized void run(){

if(shareVar==0){

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

shareVar++;

if(shareVar==5){

try{

thiswait(); //(4)

}

catch(InterruptedException e){}

}

}

}

if(shareVar!=0){

Systemoutprint(ThreadcurrentThread()getName());

Systemoutprintln(" shareVar = " + shareVar);

thisnotify(); //(5)

}

}

}

public class TestThread{

public static void main(String[] args){

TestThreadMethod t1 = new TestThreadMethod("t1");

TestThreadMethod t2 = new TestThreadMethod("t2");

t1start(); //(1)

//t1start(); (2)

t2start(); //(3)

}}

运行结果为:

t2 shareVar = 5

因为t1和t2是两个不同对象,所以线程t2调用代码(5)不能唤起线程t1。如果去掉代码(2)的注释,并注释掉代码(3),结果为:

t1 shareVar = 5

t1 shareVar = 10

这是因为,当代码(1)的线程执行到代码(4)时,它进入停滞状态,并释放对象的锁状态。接着,代码(2)的线程执行run(),由于此时shareVar值为5,所以执行打印语句并调用代码(5)使代码(1)的线程进入可执行状态,然后代码(2)的线程结束。当代码(1)的线程重新执行后,它接着执行for()循环一直到shareVar=10,然后打印shareVar。

#p#32 wait()、notify()和synchronized

waite()和notify()因为会对对象的“锁标志”进行 *** 作,所以它们必须在synchronized函数或synchronized block中进行调用。如果在non-synchronized函数或non-synchronized block中进行调用,虽然能编译通过,但在运行时会发生IllegalMonitorStateException的异常。

例18:

class TestThreadMethod extends Thread{

public int shareVar = 0;

public TestThreadMethod(String name){

super(name);

new Notifier(this);

}

public synchronized void run(){

if(shareVar==0){

for(int i=0; i<5; i++){

shareVar++;

Systemoutprintln("i = " + shareVar);

try{

Systemoutprintln("wait");

thiswait();

}

catch(InterruptedException e){}

}}

}

}

class Notifier extends Thread{

private TestThreadMethod ttm;

Notifier(TestThreadMethod t){

ttm = t;

start();

}

public void run(){

while(true){

try{

sleep(2000);

}

catch(InterruptedException e){}

/1 要同步的不是当前对象的做法 /

synchronized(ttm){

Systemoutprintln("notify");

ttmnotify();

}}

}

}

public class TestThread{

public static void main(String[] args){

TestThreadMethod t1 = new TestThreadMethod("t1");

t1start();

}

}

运行结果为:

i = 1

wait

notify

i = 2

wait

notify

i = 3

wait

notify

i = 4

wait

notify

i = 5

wait

notify

4 wait()、notify()、notifyAll()和suspend()、resume()、sleep()的讨论

41 这两组函数的区别

1) wait()使当前线程进入停滞状态时,还会释放当前线程所占有的“锁标志”,从而使线程对象中的synchronized资源可被对象中别的线程使用;而suspend()和sleep()使当前线程进入停滞状态时不会释放当前线程所占有的“锁标志”。

2) 前一组函数必须在synchronized函数或synchronized block中调用,否则在运行时会产生错误;而后一组函数可以non-synchronized函数和synchronized block中调用。

42 这两组函数的取舍

Java2已不建议使用后一组函数。因为在调用suspend()时不会释放当前线程所取得的“锁标志”,这样很容易造成“死锁”。

引起这个问题一个很有可能的原因是队列管理器在不正常停止后,虽然ps -ef | grep mq看不到此队列管理器的进程,但此MQ队列管理器的进程占用的信号灯和共享内存却没有被释放掉。解决办法如下:

1 先查看是否有此队列管理器残留的 信号灯和共享内存。命令如下:

ipcs -a | grep mq

2 如果有,使用ipcrm命令清除 残留的信号灯和共享内存,命令如下:

ipcrm -s <semphore id>

ipcrm -m <shared memory id >

3 再次启动MQ队列管理器

多线程环境中,通过队列可以很容易实现线程间数据共享,比如经典的“生产者”和“消费者”模型中,通过队列可以很便利地实现两者之间的数据共享;同时作为BlockingQueue的使用者,我们不需要关心什么时候需要阻塞线程,什么时候需要唤醒线程,因为这一切BlockingQueue的实现者都给一手包办了。

基于数组的阻塞队列实现,在ArrayBlockingQueue内部,维护了一个定长数组,以便缓存队列中的数据对象,另外还保存着两个整形变量,分别标识着队列的头部和尾部在数组中的位置。

ArrayBlockingQueue在生产者放入数据和消费者获取数据,都是共用同一个锁对象,由此也意味着两者无法真正并行运行,而在创建ArrayBlockingQueue时,我们还可以控制对象的内部锁是否采用公平锁,默认采用非公平锁。

按照实现原理来分析,ArrayBlockingQueue完全可以采用分离锁,从而实现生产者和消费者 *** 作的完全并行运行。

基于链表的阻塞队列,其内部也维持着一个数据缓冲队列(由一个链表构成),当生产者往队列中放入一个数据时,队列会从生产者手中获取数据,并缓存在队列内部,而生产者立即返回;只有当队列缓冲区达到最大值缓存容量时(LinkedBlockingQueue可以通过构造函数指定该值),才会阻塞生产者队列,直到消费者从队列中消费掉一份数据,生产者线程会被唤醒,反之对于消费者这端的处理也基于同样的原理。

对于生产者端和消费者端分别采用了独立的锁来控制数据同步,这也意味着在高并发的情况下生产者和消费者可以并行地 *** 作队列中的数据,以此来提高整个队列的并发性能。

ArrayBlockingQueue和LinkedBlockingQueue间还有一个明显的不同之处在于,前者在插入或删除元素时不会产生或销毁任何额外的对象实例,而后者则会生成一个额外的Node对象。这在长时间内需要高效并发地处理大批量数据的系统中,其对于GC的影响还是存在一定的区别。如果没有指定其容量大小,LinkedBlockingQueue会默认一个类似无限大小的容量(IntegerMAX_VALUE),这样的话,如果生产者的速度一旦大于消费者的速度,也许还没有等到队列满阻塞产生,系统内存就有可能已被消耗殆尽了。

ArrayBlockingQueue和LinkedBlockingQueue是两个最普通也是最常用的阻塞队列,一般情况下,在处理多线程间的生产者消费者问题,使用这两个类足以。

DelayQueue中的元素只有当其指定的延迟时间到了,才能够从队列中获取到该元素。DelayQueue是一个没有大小限制的队列,因此往队列中插入数据的 *** 作(生产者)永远不会被阻塞,而只有获取数据的 *** 作(消费者)才会被阻塞。

DelayQueue用于放置实现了Delayed接口的对象,其中的对象只能在其到期时才能从队列中取走。这种队列是有序的,即队头对象的延迟到期时间最长。注意:不能将null元素放置到这种队列中。

Delayed 是一种混合风格的接口,用来标记那些应该在给定延迟时间之后执行的对象。Delayed扩展了Comparable接口,比较的基准为延时的时间值,Delayed接口的实现类getDelay的返回值应为固定值(final)。DelayQueue内部是使用PriorityQueue实现的。

考虑以下场景:

一种笨笨的办法就是,使用一个后台线程,遍历所有对象,挨个检查。这种笨笨的办法简单好用,但是对象数量过多时,可能存在性能问题,检查间隔时间不好设置,间隔时间过大,影响精确度,多小则存在效率问题。而且做不到按超时的时间顺序处理。

这场景,使用DelayQueue最适合了,详情查看 DelayedQueue学习笔记 ; 精巧好用的DelayQueue

基于优先级的阻塞队列(优先级的判断通过构造函数传入的Compator对象来决定),需要注意PriorityBlockingQueue并不会阻塞数据生产者,而只会在没有可消费的数据时,阻塞数据的消费者。

使用时,若生产者生产数据的速度快于消费者消费数据的速度,随着长时间的运行,可能会耗尽所有的可用堆内存空间。在实现PriorityBlockingQueue时,内部控制线程同步的锁采用的是公平锁。

SynchronousQueue是一个内部只能包含零个元素的队列。插入元素到队列的线程被阻塞,直到另一个线程从队列中获取元素。同样,如果线程尝试获取元素并且当前没有线程在插入元素,则该线程将被阻塞,直到有线程将元素插入队列

声明一个SynchronousQueue有公平模式和非公平模式,区别如下:

参考: Java多线程-工具篇-BlockingQueue

12 SynchronousQueue

简单问题复杂化了。

线程池,本身有任务队列;

还要用到数据队列;

两把锁;

一把数据锁就解决的问题。

自己构建一个blockingqueue,注入到m个生产者线程及n个消费者线程中;

生产者线程不停的生产,往queue里put(),如果队列队列满了,线程wait挂起;

消费者线程不停的消费,从queue里take(),如过队列空了,线程自动挂起;

BlockingQueue<T> queue = new ArrayBlockingQueue<T>(1000);

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

new ConsumerThread(queue)start();

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

new ProducerThread(queue)start();

以上就是关于在JAVA中怎么实现消息队列全部的内容,包括:在JAVA中怎么实现消息队列、请问用java连接MQ时,如何获得某一个队列管理器下所有队列名称。、线程池-参数篇:2.队列等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/9811697.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-02
下一篇 2023-05-02

发表评论

登录后才能评论

评论列表(0条)

保存