java中的队列都有哪些
常见的有:
有界队列:
ArrayBlockingQueue
LinkedBlockingQuene
priorityBlockingQuene(具有优先级的队列)
无界队列:
SynchronousQuene
java中queue的使用方法?
java中的queue类是队列数据结构管理类。在它里边的元素可以按照添加它们的相同顺序被移除。
队列通常(但并非一定)以 FIFO(先进先出)的方式排序各个元素。不过优先级队列和 LIFO 队列(或堆栈)例外,前者根据提供的比较器或元素的自然顺序对元素进行排序,后者按 LIFO(后进先出)的方式对元素进行排序。无论使用哪种排序方式,队列的头都是调用remove()或poll()所移除的元素。在 FIFO 队列中,所有的新元素都插入队列的末尾。其他种类的队列可能使用不同的元素放置规则。每个Queue实现必须指定其顺序属性。
offer 添加一个元素并返回true 如果队列已满,则返回false
poll 移除并返问队列头部的元素 如果队列为空,则返回null
peek 返回队列头部的元素 如果队列为空,则返回null
put 添加一个元素 如果队列满,则阻塞
take 移除并返回队列头部的元素 如果队列为空,则阻塞
element 返回队列头部的元素 如果队列为空,则抛出一个NoSuchElementException异常
add 增加一个元索 如果队列已满,则抛出一个IIIegaISlabEepeplian异常
remove 移除并返回队列头部的元素 如果队列为空,则抛出一个
NoSuchElementException异常
注意:poll和peek方法出错进返回null。因此,向队列中插入null值是不合法的。
还有带超时的offer和poll方法重载,例如,下面的调用:
boolean success = q.offer(x,100,TimeUnit.MILLISECONDS);
尝试在100毫秒内向队列尾部插入一个元素。如果成功,立即返回true;否则,当到达超时进,返回false。同样地,调用:
Object head = q.poll(100, TimeUnit.MILLISECONDS);
如果在100毫秒内成功地移除了队列头元素,则立即返回头元素;否则在到达超时时,返回null。
阻塞操作有put和take。put方法在队列满时阻塞,take方法在队列空时阻塞。
Queue接口与List、Set同一级别,都是继承了Collection接口。LinkedList实现了Queue接 口。Queue接口窄化了对LinkedList的方法的访问权限(即在方法中的参数类型如果是Queue时,就完全只能访问Queue接口所定义的方法 了,而不能直接访问 LinkedList的非Queue的方法),以使得只有恰当的方法才可以使用。BlockingQueue 继承了Queue接口。
在JAVA中怎么实现消息队列
java中的消息队列
消息队列是线程间通讯的手段:
import java.util.*
public class MsgQueue{
private Vector queue = null;
public MsgQueue(){
queue = new Vector();
}
public synchronized void send(Object o)
{
queue.addElement(o);
}
public synchronized Object recv()
{
if(queue.size()==0)
return null;
Object o = queue.firstElement();
queue.removeElementAt(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下的常用函数函数
2.1 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; i5; i++){
shareVar++;
if(shareVar==5){
this.suspend(); //(1)
}}}
else{
System.out.print(Thread.currentThread().getName());
System.out.println(” shareVar = ” + shareVar);
this.resume(); //(2)
}}
}
public class TestThread{
public static void main(String[] args){
TestThreadMethod t1 = new TestThreadMethod(“t1”);
TestThreadMethod t2 = new TestThreadMethod(“t2”);
t1.start(); //(5)
//t1.start(); //(3)
t2.start(); //(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#2.2 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; i3; i++){
System.out.print(Thread.currentThread().getName());
System.out.println(” : ” + i);
try{
Thread.sleep(100); //(4)
}
catch(InterruptedException e){
System.out.println(“Interrupted”);
}}}
}
public class TestThread{public static void main(String[] args){
TestThreadMethod t1 = new TestThreadMethod(“t1”);
TestThreadMethod t2 = new TestThreadMethod(“t2”);
t1.start(); (1)
t1.start(); (2)
//t2.start(); (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; i5; i++){
System.out.print(Thread.currentThread().getName());
System.out.println(” : ” + i);
try{
if(Thread.currentThread().getName().equals(“t1”))
Thread.sleep(200);
else
Thread.sleep(100);
}
catch(InterruptedException e){
System.out.println(“Interrupted”);
}}
}}
public class TestThread{public static void main(String[] args){
TestThreadMethod t1 = new TestThreadMethod(“t1”);
TestThreadMethod t2 = new TestThreadMethod(“t2”);
t1.start();
//t1.start();
t2.start();
}}
运行结果为:
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#2.3 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; i4; i++){
System.out.print(Thread.currentThread().getName());
System.out.println(” : ” + i);
Thread.yield();
}}
}
public class TestThread{public static void main(String[] args){
TestThreadMethod t1 = new TestThreadMethod(“t1”);
TestThreadMethod t2 = new TestThreadMethod(“t2”);
t1.start();
t1.start(); //(1)
//t2.start(); (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(),但它马上又被执行了。
2.4 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; i4; i++){
System.out.print(Thread.currentThread().getName());
System.out.println(” : ” + i);
//Thread.yield(); (1)
/* (2) */
try{
Thread.sleep(3000);
}
catch(InterruptedException e){
System.out.println(“Interrupted”);
}}}
}
public class TestThread{
public static void main(String[] args){
TestThreadMethod t1 = new TestThreadMethod(“t1”);
TestThreadMethod t2 = new TestThreadMethod(“t2”);
t1.setPriority(Thread.MAX_PRIORITY);
t2.setPriority(Thread.MIN_PRIORITY);
t1.start();
t2.start();
}
}
运行结果为:
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(),不同优先级的线程永远不会得到执行机会。
2.5 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; i4; i++){
System.out.println(” ” + i);
try{
Thread.sleep(3000);
}
catch(InterruptedException e){
System.out.println(“Interrupted”);
}
}
}
}
public class TestThread{
public static void main(String[] args){
TestThreadMethod t1 = new TestThreadMethod(“t1”);
t1.start();
try{
t1.join();
}
catch(InterruptedException e){}
t1.start();
}
}
运行结果为:
1
2
3
1
2
3
#p#3. class Object下常用的线程函数
wait()、notify()和notifyAll()这三个函数由java.lang.Object类提供,用于协调多个线程对共享数据的存取。
3.1 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; i10; i++){
shareVar++;
if(shareVar==5){
try{
this.wait(); //(4)
}
catch(InterruptedException e){}
}
}
}
if(shareVar!=0){
System.out.print(Thread.currentThread().getName());
System.out.println(” shareVar = ” + shareVar);
this.notify(); //(5)
}
}
}
public class TestThread{
public static void main(String[] args){
TestThreadMethod t1 = new TestThreadMethod(“t1”);
TestThreadMethod t2 = new TestThreadMethod(“t2”);
t1.start(); //(1)
//t1.start(); (2)
t2.start(); //(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#3.2 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; i5; i++){
shareVar++;
System.out.println(“i = ” + shareVar);
try{
System.out.println(“wait……”);
this.wait();
}
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){
System.out.println(“notify……”);
ttm.notify();
}}
}
}
public class TestThread{
public static void main(String[] args){
TestThreadMethod t1 = new TestThreadMethod(“t1”);
t1.start();
}
}
运行结果为:
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()的讨论
4.1 这两组函数的区别
1) wait()使当前线程进入停滞状态时,还会释放当前线程所占有的“锁标志”,从而使线程对象中的synchronized资源可被对象中别的线程使用;而suspend()和sleep()使当前线程进入停滞状态时不会释放当前线程所占有的“锁标志”。
2) 前一组函数必须在synchronized函数或synchronized block中调用,否则在运行时会产生错误;而后一组函数可以non-synchronized函数和synchronized block中调用。
4.2 这两组函数的取舍
Java2已不建议使用后一组函数。因为在调用suspend()时不会释放当前线程所取得的“锁标志”,这样很容易造成“死锁”。
JAVA中队列和栈的区别
队列(Queue):是限定只能在表的一端进行插入和在另一端进行删除操作的线性表;
栈(Stack):是限定只能在表的一端进行插入和删除操作的线性表。
区别如下:
一、规则不同
1. 队列:先进先出(First In First Out)FIFO
2. 栈:先进后出(First In Last Out )FILO
二、对插入和删除操作的限定不同
1. 队列:只能在表的一端进行插入,并在表的另一端进行删除;
2. 栈:只能在表的一端插入和删除。
三、遍历数据速度不同
1.
队列:基于地址指针进行遍历,而且可以从头部或者尾部进行遍历,但不能同时遍历,无需开辟空间,因为在遍历的过程中不影响数据结构,所以遍历速度要快;
2.
栈:只能从顶部取数据,也就是说最先进入栈底的,需要遍历整个栈才能取出来,而且在遍历数据的同时需要为数据开辟临时空间,保持数据在遍历前的一致性。
java多线程共同操作同一个队列,怎么实现?
具体代码如下:
以下是两个线程:
import java.util.*;
public class Thread_List_Operation {
//假设有这么一个队列
static List list = new LinkedList();
public static void main(String[] args) {
Thread t;
t = new Thread(new T1());
t.start();
t = new Thread(new T2());
t.start();
}
}
//线程T1,用来给list添加新元素
class T1 implements Runnable{
void getElemt(Object o){
Thread_List_Operation.list.add(o);
System.out.println(Thread.currentThread().getName() + “为队列添加了一个元素”);
}
@Override
public void run() {
for (int i = 0; i 10; i++) {
getElemt(new Integer(1));
}
}
}
//线程T2,用来给list添加新元素
class T2 implements Runnable{
void getElemt(Object o){
Thread_List_Operation.list.add(o);
System.out.println(Thread.currentThread().getName() + “为队列添加了一个元素”);
}
@Override
public void run() {
for (int i = 0; i 10; i++) {
getElemt(new Integer(1));
}
}
}
//结果(乱序)
Thread-0为队列添加了一个元素
Thread-1为队列添加了一个元素
Thread-0为队列添加了一个元素
Thread-1为队列添加了一个元素
Thread-1为队列添加了一个元素
Thread-1为队列添加了一个元素
Thread-1为队列添加了一个元素
Thread-1为队列添加了一个元素
Thread-1为队列添加了一个元素
Thread-1为队列添加了一个元素
Thread-1为队列添加了一个元素
Thread-1为队列添加了一个元素
Thread-0为队列添加了一个元素
Thread-0为队列添加了一个元素
Thread-0为队列添加了一个元素
Thread-0为队列添加了一个元素
Thread-0为队列添加了一个元素
Thread-0为队列添加了一个元素
Thread-0为队列添加了一个元素
Thread-0为队列添加了一个元素
java 用什么实现 FIFO队列?
java使用数据结构来实现FIFO先进先出的队列,实例如下:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package linkedlisttest;
import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
/**
*
* @author Vicky.H
* @email eclipser@163.com
*/
public class FIFOTest {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
FIFOA fifo = new FIFOImplA(5);
for (int i = 0; i 20; i++) {
A a = new A(“A:” + i);
A head = fifo.addLastSafe(a);
System.out.println(i + “\thead:” + head + “\tsize:” + fifo.size());
}
System.out.println(“—————“);
System.out.println(“弹出数据”);
ListA polls = fifo.setMaxSize(3);
for (A a : polls) {
System.out.println(“\thead:” + a);
}
System.out.println(“剩余数据”);
for (A a : fifo) {
System.out.println(“\thead:” + a);
}
System.out.println(fifo.size());
}
}
interface FIFOT extends ListT, DequeT, Cloneable, java.io.Serializable {
/**
* 向最后添加一个新的,如果长度超过允许的最大值,则弹出一个 *
*/
T addLastSafe(T addLast);
/**
* 弹出head,如果Size = 0返回null。而不同于pop抛出异常
* @return
*/
T pollSafe();
/**
* 获得最大保存
*
* @return
*/
int getMaxSize();
/**
* 设置最大存储范围
*
* @return 返回的是,因为改变了队列大小,导致弹出的head
*/
ListT setMaxSize(int maxSize);
}
class FIFOImplT extends LinkedListT implements FIFOT {
private int maxSize = Integer.MAX_VALUE;
private final Object synObj = new Object();
public FIFOImpl() {
super();
}
public FIFOImpl(int maxSize) {
super();
this.maxSize = maxSize;
}
@Override
public T addLastSafe(T addLast) {
synchronized (synObj) {
T head = null;
while (size() = maxSize) {
head = poll();
}
addLast(addLast);
return head;
}
}
@Override
public T pollSafe() {
synchronized (synObj) {
return poll();
}
}
@Override
public ListT setMaxSize(int maxSize) {
ListT list = null;
if (maxSize this.maxSize) {
list = new ArrayListT();
synchronized (synObj) {
while (size() maxSize) {
list.add(poll());
}
}
}
this.maxSize = maxSize;
return list;
}
@Override
public int getMaxSize() {
return this.maxSize;
}
}
class A {
private String name;
public A() {
}
public A(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return “A{” + “name=” + name + ‘}’;
}
}