java串行接口调用优化
准备面试总结下
1.completablefuture
static threadpoolexecutor poolexecutor = new threadpoolexecutor(10, 20, 1000l, timeunit.microseconds, new arrayblockingqueue<>(100)); public static void main(string[] args) throws executionexception, interruptedexception { completablefuture<integer> task1 = completablefuture.supplyasync(() -> { try { system.out.println("task1"); thread.sleep(1000); } catch (interruptedexception e) { throw new runtimeexception(e); } return 1000; }, poolexecutor); completablefuture<integer> task2 = completablefuture.supplyasync(() -> { try { system.out.println("task2"); thread.sleep(2000); } catch (interruptedexception e) { throw new runtimeexception(e); } return 2000; }, poolexecutor); completablefuture<integer> task3 = completablefuture.supplyasync(() -> { try { system.out.println("task3"); thread.sleep(10000); } catch (interruptedexception e) { throw new runtimeexception(e); } return 5000; }, poolexecutor); integer result1 = task1.get(); system.out.println(result1); integer result2 = task2.get(); system.out.println(result2); integer result3 = task3.get(); system.out.println(result3); completablefuture<void> voidcompletablefuture = completablefuture.allof(task1, task2, task3); poolexecutor.shutdown(); system.out.println("执行完毕"); }
2.coutdownlatch
static hashmap<string, integer> map = new hashmap<string, integer>(); public static void main(string[] args) throws interruptedexception, executionexception { threadpoolexecutor poolexecutor = new threadpoolexecutor(10, 20, 1000l, timeunit.microseconds, new arrayblockingqueue<>(100)); countdownlatch countdownlatch = new countdownlatch(3); future<integer> task1 = poolexecutor.submit(new callable<integer>() { @override public integer call() throws exception { system.out.println("任务1"); thread.sleep(1000); system.out.println("任务1结束"); countdownlatch.countdown(); return 1000; } }); future<integer> task2 = poolexecutor.submit(new callable<integer>() { @override public integer call() throws exception { system.out.println("任务2"); thread.sleep(500); system.out.println("任务2结束"); countdownlatch.countdown(); return 500; } }); future<integer> task3 = poolexecutor.submit(new callable<integer>() { @override public integer call() throws exception { system.out.println("任务3"); thread.sleep(2000); system.out.println("任务3结束"); countdownlatch.countdown(); return 2000; } }); map.put("task1", task1.get()); map.put("task2", task1.get()); map.put("task3", task1.get()); system.out.println("线程跑完了"); countdownlatch.await(); system.out.println("---------------任务执行结束-------------"); poolexecutor.shutdown(); }
3.阻塞获取异步调用结果
public static void main(string[] args) throws executionexception, interruptedexception { executorservice executorservice = executors.newfixedthreadpool(3); future<string> submit = executorservice.submit(new callable<string>() { @override public string call() throws exception { thread.sleep(1000); return "its done"; } }); while (true){ if (submit.isdone()){ system.out.println(submit.get()); break; } system.out.println(submit.isdone()); } }
4.除了上面两个方法 还有 cyclicbarrier,semaphore也都可以实现,可以自己尝试下
java串口程序的调用
rxtx串口插件的使用方法(windows平台)
1、把rxtxparallel.dll、rxtxserial.dll拷贝到:c:\windows\system32下。
2、如果是在开发的时候(jdk),需要把rxtxcomm.jar、rxtxparallel.dll、rxtxserial.dll拷贝到…\jre…\lib\ext下;如:d:\program files\java\jre1.6.0_02\lib\ext
3、需要选中项目右键->preperties->java build path->libraries->选择external folder–>选择rxtxcomm.jar.
- 拷贝 rxtxcomm.jar 到 <java_home>\jre\lib\ext目录中;
- 拷贝 rxtxserial.dll 到 <java_home>\jre\bin目录中;
- 拷贝 rxtxparallel.dll 到 <java_home>\jre\bin目录中;
其中<java_home>为jdk安装路径
下面是一些程序运行测试写的方法
package com.serialport; import java.io.ioexception; import java.io.inputstream; import java.io.outputstream; import java.util.date; import java.util.enumeration; import java.util.hashset; import java.util.toomanylistenersexception; import java.util.concurrent.blockingqueue; import java.util.concurrent.linkedblockingqueue; import com.readtable.hextest; import gnu.io.commport; import gnu.io.commportidentifier; import gnu.io.portinuseexception; import gnu.io.serialport; import gnu.io.serialportevent; import gnu.io.serialporteventlistener; import gnu.io.unsupportedcommoperationexception; /** * 这个是一个更加完善的串口调用及接收函数类 * @author administrator * */ public class serialreceiver extends thread implements serialporteventlistener{ hextest hext2 = new hextest(); static commportidentifier portid; // 串口通信管理类 static enumeration<?> portlist; // 有效连接上的端口的枚举 static inputstream inputstream; //从串口来数据的输入流 static outputstream outputstream;// 向串口输出的流 static serialport serialport; // 串口的引用 private static byte[] readbuffer = new byte[1024]; // 4k的buffer空间,缓存串口读入的数据 int numbytes; //buffer中的实际数据字节数 ,每一次读取的字节数据 // 堵塞队列用来存放读到的数据 private blockingqueue<string> msgqueue = new linkedblockingqueue<string>(); //其他的常量设置 //端口是否打开了 boolean isopen = false; // 端口读入数据事件触发后,等待n毫秒后再读取,以便让数据一次性读完 public static int params_delay = 1000; // 延时等待端口数据准备的时间 public static int params_timeout = 2000; // 超时时间 public static string params_port = "com4"; // 端口名称 public static int params_rate = 2400; // 波特率 public static int params_databits = 8; // 数据位 public static int params_stopbits = 1; // 停止位 public static int params_parity = 1; // 奇偶校验 /** * serialport eventlistene 的方法,持续监听端口上是否有数据流 */ @override public void serialevent(serialportevent event) { // todo auto-generated method stub switch (event.geteventtype()) { case serialportevent.data_available:// 当有可用数据时读取数据 recetest(); break; } } /** * 接收的数据进行打印测试 */ private void recetest() { try { numbytes = 0; while (inputstream.available() > 0) { numbytes += inputstream.read(readbuffer,numbytes,1024); } if (numbytes > 0) { msgqueue.add(new date() +"方法2接收的字节数为:"+numbytes+ " 收到的数据为:-----" + hext2.arraytohexstr(readbuffer, 0, numbytes)); readbuffer = new byte[1024]; //重新构造缓冲对象,否则有可能会影响接下来接收的数据 } else { msgqueue.add("额------没有读到数据"); } } catch (ioexception e) { } } /** * 根据串口名,获取串口接口 * @param portname * @return */ public serialport openserialport(string portname) { //获取设备上的所有端口 portlist = commportidentifier.getportidentifiers(); while (portlist.hasmoreelements()) { // 获取相应串口对象 portid = (commportidentifier) portlist.nextelement(); system.out.println("设备类型:--->" + portid.getporttype()); system.out.println("设备名称:--->" + portid.getname()); //判断端口类型是否为串口 if (portid.getporttype() == commportidentifier.port_serial) { // 判断如果输入的串口名对应的串口存在,就打开该串口 if (portid.getname().equals(portname)) { try { // 打开串口名字为com_4(名字任意),延迟为2毫秒 serialport = (serialport) portid.open("com_3", 2000); return serialport; } catch (portinuseexception e) { e.printstacktrace(); return null; } } } } return null; } /** * 打开串口的函数 * @param portname 串口名 * @param bitrate 波特率 * @param databit 数据位 * @param stopbit 停止位 * @param parity 校验方式:奇 偶 无 * @return */ public int opencomport(string portname,int bitrate,int databit,int stopbit,int parity) { serialport = openserialport(portname); if(serialport != null) { // 设置当前串口的输入输出流 try { inputstream = serialport.getinputstream(); outputstream = serialport.getoutputstream(); } catch (ioexception e) { e.printstacktrace(); return 0; } // 给当前串口添加一个监听器 try { serialport.addeventlistener(this); } catch (toomanylistenersexception e) { e.printstacktrace(); return 0; } // 设置监听器生效,即:当有数据时通知 serialport.notifyondataavailable(true); //给串口设置一些参数 try { // 比特率、数据位、停止位、奇偶校验位 serialport.setserialportparams( bitrate,databit,stopbit,parity); } catch (unsupportedcommoperationexception e) { e.printstacktrace(); return 0; } return 1; } return 0; } @override public void run() { // todo auto-generated method stub try { system.out.println("--------------任务处理线程运行了--------------"); while (true) { //如果堵塞队列中存在数据就将其输出 if (msgqueue.size() > 0) { system.out.println(msgqueue.take()); } } } catch (interruptedexception e) { // todo auto-generated catch block e.printstacktrace(); } } public static void main(string[] args) { serialreceiver cread = new serialreceiver(); params_port = "com3"; // 端口名称 params_rate = 2400; // 波特率 params_databits = serialport.databits_8; //数据位 params_stopbits = serialport.stopbits_1; // 停止位 params_parity = serialport.parity_even; // 奇偶校验 int i = cread.opencomport(params_port,params_rate,params_databits, params_stopbits,params_parity); if (i == 1) { // 启动线程来处理收到的数据 cread.start(); try { //发送指令 hextest hext = new hextest(); byte[] bst = hext.readtable07(1,1, 0,3); outputstream.write(bst, 0,bst.length); } catch (ioexception e) { // todo auto-generated catch block e.printstacktrace(); } } else { return; } } }
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论