【多线程】 java线程实例(测试阻塞队列&&线程池)

时间:2020-12-08 17:20:32
<span style="font-size:14px;">//测试阻塞队列
package com.moshenglv.dms.Demo;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

public class Demo02 {
//从队列接收的线程
Thread tom;
//向队列发送 的线程
Thread jerry;

BlockingQueue queue;//阻塞队列

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

Thread.sleep(100);

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

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

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


public void startT(){
queue = new LinkedBlockingQueue(3);//用链表实现阻塞队列
tom = new Tom();
jerry = new jerry();
jerry.start();
tom.start();

}

public static void main(String[] args) {
new Demo02().startT();



}



}



//测试线程池

package com.moshenglv.dms.Demo;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

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



//Executor是抽象类执行器,利用工厂方法
Executor executor = Executors.newFixedThreadPool(3);//从工厂获得线程池对象
executor.execute(new Dog("金毛"));//第一个线程
executor.execute(new Dog("中华田园犬"));//第二个线程
executor.execute(new Dog("哈士奇"));//第三个线程
executor.execute(new Dog("泰迪"));//第四个线程,因为线程池大小为3,所以当前三个有人退出时开始执行
executor.execute(new Dog("藏獒"));//第五个线程,等前面线程运行完
}
}
//创建一个线程,实现里面的run方法
class Dog implements Runnable{
String name;
public Dog(String name){
this.name = name;
}

public void run() {
for(int i =0;i<3;i++){
System.out.println(name + "在跑"+i);
try{
Thread.sleep(1000);
}catch(Exception e){

}
}

System.out.println(name+" over");
}
}</span>