项目中使用java多线程记录
很多时候,项目中会遇到各种并发啊,异步处理啊,比如一个接口中,又要处理吃饭,又要立马做好饭,那么就搞一个线程池,单独去处理做饭,啥也不管,先弄个凉菜上去给客人吃着再说。好,废话不喜欢,代码直接撸。如下是实际项目中各处使用部分代码。
描述,业务相关不用理会,只需要看此代码中使用的Executors.newScheduledThreadPool(1),是做了一个项目启动初始化,加载此项,作为启动一个线程池来多少秒延迟多少秒执行一次,这样去处理一些业务,那个MSG是我这边的websocket推送。 import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.alibaba.fastjson.JSONObject; import javax.annotation.PostConstruct; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; @Component public class YTSchedule { private static Logger log = LoggerFactory.getLogger(YTSchedule.class); @Autowired private CommonConfig config; @Autowired private PushFaceJob pushface; @PostConstruct public void init(){ if(config.getFaceType() ==1 ||config.getFaceType() ==3){ Executors.newScheduledThreadPool(1).scheduleAtFixedRate(() -> { try{ pushface.faceJob(); pushface.pushHitAlertFaceJob(); pushface.pushRealPowerFaceJob(); JSONObject hp = new JSONObject(); hp.put("name","ck"); hp.put("age", 23); List list = new ArrayList(); JSONObject temp = new JSONObject(); temp.put("filter","afads"); JSONObject v = new JSONObject(); v.put("villageCode","310104006001"); temp.put("deep",v); list.add(temp); temp.put("filter","12345"); temp = new JSONObject(); list.add(temp); hp.put("list",list); Map map = new HashMap<>(); map.put("test", "123545"); hp.put("value",map); Msg msg = new Msg("hp",hp); msg.send(); }catch (Exception e){ e.printStackTrace(); } },20,8,TimeUnit.SECONDS);//待所有服务都启动完成后执行 } } }
描述:这是搞得一个简单的利用ListenableFuture实现监听的例子。 解释: ListenableFuture是可以监听的Future,它是对java原生Future的扩展增强。Future表示一个异步计算任务,当任务完成时可以得到计算结果。如果希望计算完成时马上就拿到结果展示给用户或者做另外的计算,就必须使用另一个线程不断的查询计算状态。这样做会使得代码复杂,且效率低下。如果使用ListenableFuture,Guava会帮助检测Future是否完成了,如果完成就自动调用回调函数,这样可以减少并发程序的复杂度。 import com.google.common.util.concurrent.*; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.Random; import java.util.concurrent.Callable; import java.util.concurrent.Executors; public class hello { public static void main(String[] args) { ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(1)); // ExecutorService service=Executors.newFixedThreadPool(1); ListenableFuture<String> task = service.submit(new Callable<String>() { @Override public String call() throws Exception { Thread.sleep(3000); return "hello"; } }); Futures.addCallback(task, new FutureCallback<String>() { @Override public void onSuccess(String result) { System.out.println(result); } @Override public void onFailure(Throwable t) { System.out.println(t.getLocalizedMessage()); } }); } }
JAVA修炼塔,技术世界的探知与交流,欢迎你的加入-----群号:535296702

浙公网安备 33010602011771号