线程代码实例

//测试阻塞队列

packagecom.moshenglv.dms.Demo;

importjava.util.concurrent.BlockingQueue;
importjava.util.concurrent.LinkedBlockingQueue;
importjava.util.concurrent.TimeUnit;


publicclassDemo02{
//从队列接收的线程
Threadtom;
//向队列发送的线程
Threadjerry;

BlockingQueuequeue;//阻塞队列


classTomextendsThread{
publicvoidrun(){
while(true){
try{
Strings=queue.poll(1,TimeUnit.SECONDS);//取消息,没有就等一秒,还没有null
if(s==null){
System.out.println("队列空了,木有取到...");
continue;
}
System.out.println("Tom收到:"+s);

Thread.sleep(100);

}catch(InterruptedExceptione){
e.printStackTrace();
}
}
}
}

//发送
classjerryextendsThread{
inti=0;
publicvoidrun(){
while(true){
Strings="Hi"+i;
try{
booleansuccess=queue.offer(s,5,TimeUnit.SECONDS);//如果队列满了,就等?秒钟,若还插不进就返回false
if(success){
System.out.println("添加消息成功!"+s);
i++;
}else{
System.out.println("添加不成功,队列满了,重新尝试..");
continue;
}

Thread.sleep(2000);
}catch(InterruptedExceptione){
e.printStackTrace();
}
}
}
}


publicvoidstartT(){
queue=newLinkedBlockingQueue(3);//用链表实现阻塞队列
tom=newTom();
jerry=newjerry();
jerry.start();
tom.start();

}

publicstaticvoidmain(String[]args){
newDemo02().startT();



}



}

//测试线程池

packagecom.moshenglv.dms.Demo;

importjava.util.concurrent.Executor;
importjava.util.concurrent.Executors;


publicclassdemo01{
publicstaticvoidmain(String[]args){



//Executor是抽象类执行器,利用工厂方法
Executorexecutor=Executors.newFixedThreadPool(3);//从工厂获得线程池对象
executor.execute(newDog("金毛"));//第一个线程
executor.execute(newDog("中华田园犬"));//第二个线程
executor.execute(newDog("哈士奇"));//第三个线程
executor.execute(newDog("泰迪"));//第四个线程,因为线程池大小为3,所以当前三个有人退出时开始执行
executor.execute(newDog("藏獒"));//第五个线程,等前面线程运行完
}
}

//创建一个线程,实现里面的run方法
classDogimplementsRunnable{
Stringname;
publicDog(Stringname){
this.name=name;
}

publicvoidrun(){
for(inti=0;i<3;i++){
System.out.println(name+"在跑"+i);
try{
Thread.sleep(1000);
}catch(Exceptione){

}
}

System.out.println(name+"over");
}
}

你可能感兴趣的:(代码,java线程,测试阻塞队列)