知识大全 Java Thread队列详细代码的介绍
Posted hr
篇首语:亦余心之所善兮,虽九死其犹未悔。本文由小常识网(cha138.com)小编为大家整理,主要介绍了知识大全 Java Thread队列详细代码的介绍相关的知识,希望对你有一定的参考价值。
Java Thread队列详细代码的介绍 以下文字资料是由(全榜网网www.cha138.com)小编为大家搜集整理后发布的内容,让我们赶快一起来看一下吧!
Java Thread队列一直是我们需要掌握的代码 下面我们就基本思想 建立了一个队列 为每一个Java Thread队列保存了一个对象锁 保证按顺序执行 线程启动的时候 使随机的 但是执行代码是按顺序的
import java util LinkedList;
import java util Queue;
public class ThreadTest
private static Queue qThread=new LinkedList();//线程同步对象队列
public static synchronized void putObject(Object t)
qThread offer(t);
public static synchronized Object getObject()
return qThread poll();
public static void waitThread(Object t) throws InterruptedException
synchronized(t)
t wait();
public static void notifyThread()
Object obj=ThreadTest getObject();
synchronized(obj)
obj notify();
public static void main(String[] args) throws InterruptedException
int i = ;
boolean isFirst=true;
while (i < )
Object obj=new Object();
if(i> )
isFirst=false;
ThreadTest putObject(obj);
Thread t = new Thread (isFirst obj);
Object obj =new Object();
ThreadTest putObject(obj );
Thread t = new Thread (obj );
t start();
t start();
i++;
/**
* 线程
*
* @author Harry WANG
*
*/
class Thread extends Thread
private boolean isFirst=false;
private Object obj;
public Thread (boolean f Object obj)
this isFirst=f;
this obj=obj;
@Override
public void run()
if(!this isFirst)
System out println(this getName()+ 等待 );
try
ThreadTest waitThread(obj);
catch(InterruptedException e)
e printStackTrace();
System out println( 启动 +this getName()+ );
try
sleep( );//等待 秒 为了测试
catch (InterruptedException e)
e printStackTrace();
System out println( 停止 +this getName()+ );
ThreadTest notifyThread();
class Thread extends Thread
private Object obj;
public Thread (Object obj)
this obj=obj;
@Override
public void run()
System out println(this getName()+ 等待 );
try
ThreadTest waitThread(obj);
catch(InterruptedException e)
e printStackTrace();
System out println( 启动 +this getName()+ );
try
sleep( );//等待 秒 为了测试
catch (InterruptedException e)
e printStackTrace();
System out println( 停止 +this getName()+ );
ThreadTest notifyThread();
cha138/Article/program/Java/hx/201311/27018
相关参考