本文目錄一覽:
java怎麼實現n個隊列
public class QueueE {
private Object[] data=null;
private int maxSize; //隊列容量
private int front; //隊列頭,允許刪除
private int rear; //隊列尾,允許插入
//構造函數
public Queue(){
this(10);
}
public Queue(int initialSize){
if(initialSize =0){
this.maxSize = initialSize;
data = new Object[initialSize];
front = rear =0;
}else{
throw new RuntimeException(“初始化大小不能小於0:” + initialSize);
}
}
//判空
public boolean empty(){
return rear==front?true:false;
}
//插入
public boolean add(E e){
if(rear== maxSize){
throw new RuntimeException(“隊列已滿,無法插入新的元素!”);
}else{
data[rear++]=e;
return true;
}
}
//返回隊首元素,但不刪除
public E peek(){
if(empty()){
throw new RuntimeException(“空隊列異常!”);
}else{
return (E) data[front];
}
}
//出隊
public E poll(){
if(empty()){
throw new RuntimeException(“空隊列異常!”);
}else{
E value = (E) data[front]; //保留隊列的front端的元素的值
data[front++] = null; //釋放隊列的front端的元素
return value;
}
}
//隊列長度
public int length(){
return rear-front;
}
}
在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代碼實現一個隊列
class StackT {
private VectorT v;
public Stack(){
v = new VectorT();
}
public T pop(){
if (v.size()==0) return null;
return v.get(v.size()-1);
}
public void push(T t){
v.add(t);
}
public boolean isEmpty(){
return v.size()==0;
}
}
class QueueT{
private VectorT v;
public Queue(){
v = new VectorT();
}
//入隊列
public void enqueue(T t){
v.add(t);
}
//出隊列
public T dequeue(){
if (v.size()==0) return null;
return v.get(0);
}
public boolean isEmpty(){
return v.size() == 0;
}
}
用java編一個隊列
自己寫了個簡單的實現
class QueueE{
private Object[] integerQueue;//用來當隊列
public int tail;//隊尾
public int size;//隊的長度,也可以設置一個默認值,溢出時從新申請
public Queue(int size){
integerQueue=new Object[size];
this.size=size;
tail=-1;
}
/**
* 將元素插入隊列
* @return 如果該元素已添加到此隊列,則返回 true;否則返回 false
*/
public boolean offer(E e){
if(tail size-1){
tail++;
this.integerQueue[tail]=e;
return true;
}else{
return false;
}
}
/**
* 獲取並移除此隊列的頭,如果此隊列為空,則返回 null。
*/
public E poll(){
Object tmp;
if(tail=0){
tmp=this.integerQueue[tail];
tail–;
return (E)tmp;
}else{
return null;
}
}
}
關於java合併兩個隊列
新建個隊列依次往裡放就是了。就這樣:
ArrayList a;//你已經有的a;
ArrayList b;//你已經有的b;
ArrayList c= new ArrayList();
比較a.size()大還是b.size()大,大的=e,小的=q;
for(int i=0;ie;i++){
if(iq){
c.add(a.get(i));
c.add(b.get(i));
}
if(i=q){
c.add(b.get(i));
}
}
寫的這樣也差不多了吧
java 隊列
//通過LinkedList實現隊列
package 隊列和堆棧;
import java.util.*;
public class LinkedListQueueTest {
//字段
private LinkedList list;
//無參數構造
public LinkedListQueueTest()
{
list=new LinkedList();
}
//隊列元素的個數
public int size()
{
return list.size();
}
//進入隊列
public void enqueue(Object obj)
{
list.addLast(obj);
}
//對頭出來
public Object dequeue()
{
return list.removeFirst();
}
//瀏覽對頭元素
public Object front()
{
//return list.getFirst();
return list.peekFirst();
}
//判斷隊列是否為空
public boolean isEmpty()
{
return list.isEmpty();
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
LinkedListQueueTest llq=new LinkedListQueueTest();
System.out.println(llq.isEmpty());
llq.enqueue(“147”);
llq.enqueue(“258”);
llq.enqueue(“369”);
System.out.println(llq.size());
System.out.println(“移除隊列頭元素:”+llq.dequeue());
System.out.println(llq.size());
llq.enqueue(“abc”);
llq.enqueue(“def”);
System.out.println(llq.size());
System.out.println(“查看隊列的頭元素:”+llq.front());
System.out.println(llq.size());
System.out.println(llq.isEmpty());
}
}
通過數組實現
package 隊列和堆棧;
import java.util.NoSuchElementException;
//通過數組來實現隊列
public class ArrayQueue {
//字段
public static Object[] data;
//隊列的元素個數
protected int size ;
//隊列頭
protected int head;
//隊列尾
public static int tail;
/**
*
*/
//無參數構造函數
public ArrayQueue() {
final int INITIAL_LENGTH=3;
data=new Object[INITIAL_LENGTH];
size=0;
head=0;
tail=-1;
}
//隊列元素個數方法
public int size()
{
return size;
}
public boolean isEmpty()
{
return size==0;
}
//得到隊列頭元素
public Object front()
{
if(size==0)
throw new NoSuchElementException();
return data[head];
}
//進入隊列enqueue()方法
public void enqueue(Object obj)
{
//此時隊列已經滿
if(size==data.length){
Object[] oldData=data;
data=new Object[data.length*2];
//if(head==0)
System.arraycopy(oldData, head, data, 0, oldData.length-head);
if(head0)
System.arraycopy(oldData, 0, data, head+1, tail+1);
head=0;
tail=oldData.length-1;
}
tail=(tail+1)%data.length;
size++;
data[tail]=obj;
}
//隊列的元素出隊
public Object dequeue()
{
if(size==0)
throw new NoSuchElementException();
Object ele=data[head];
//循環隊列
head=(head+1)%data.length;
size–;
return ele;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return super.toString();
}
}
通過向量實現:
//通過向量實現棧
package 隊列和堆棧;
import java.util.*;
public class VectorStackTest {
//字段
Vector v;
//構造函數
public VectorStackTest()
{
v=new Vector();
}
//元素的個數
public int size()
{
return v.size();
}
//是否為空
public boolean isEmpty()
{
return size()==0;
}
//進棧
public Object Push(Object obj)
{
v.addElement(obj);
return obj;
}
//出棧方法
public Object Pop()
{
int len=size();
Object obj=Peek();
v.removeElementAt(len-1);
return obj;
}
//查看棧頂元素
public Object Peek()
{
int len = size();
if (len == 0)
throw new EmptyStackException();
return v.elementAt(len – 1);
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
VectorStackTest vst=new VectorStackTest();
System.out.println(“大小:”+vst.size());
vst.Push(“123”);
vst.Push(“456”);
vst.Push(“789”);
vst.Push(“abc”);
System.out.println(“大小:”+vst.size());
System.out.println(“棧頂:”+vst.Peek());
System.out.println(“出棧:”+vst.Pop());
vst.Push(“def”);
vst.Push(“147”);
System.out.println(“大小:”+vst.size());
System.out.println(“棧頂:”+vst.Peek());
System.out.println(“出棧:”+vst.Pop());
System.out.println(vst.Peek());
vst.Push(“def”);
vst.Push(“147”);
System.out.println(vst.Pop());
System.out.println(vst.Pop());
System.out.println(vst.Peek());
System.out.println(vst.Pop());
System.out.println(vst.Pop());
vst.Push(“1aadf”);
vst.Push(“2dafad”);
vst.Push(“123789”);
System.out.println(vst.Pop());
System.out.println(vst.Peek());
System.out.println(vst.Pop());
System.out.println(vst.Peek());
System.out.println(“——————end————“);
VectorStackTest llst=new VectorStackTest();
llst.Push(“123”);
llst.Push(“456”);
System.out.println(“棧頂:”+llst.Peek());
System.out.println(“出棧:”+llst.Pop());
System.out.println(llst.Peek());
llst.Push(“789”);
llst.Push(“abc”);
System.out.println(“棧頂:”+llst.Peek());
System.out.println(“出棧:”+llst.Pop());
System.out.println(llst.size());
System.out.println(“棧頂:”+llst.Peek());
}
}
推薦:都看API文檔。有疑問可以問我,QQ:285479197
原創文章,作者:DXGD,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/142584.html