在学习java的过程中会慢慢发现,java的知识量丰富且庞大,难以轻易掌握。学习java的过程其实也就是在不断提升自己的耐性与韧性的过程。今天就来为大家介绍一下,java中SerialBuffer的定义,并且之后会用实际的代码为大家展示。
首先,我们可以了解到的是,SerialBuffer是本类库中所定义的串口缓冲区,它定义了往该缓冲区中写入数据和从该缓冲区中读取数据所需要的函数。主要有下面这些:
1.public synchronized String GetMsg(int Length)
本函数从串口(缓冲区)中读取指定长度的一个字符串。参数Length指定所返回字符串的长度。
2.public synchronized void PutChar(int c)
本函数往串口缓冲区中写入一个字符,参数c是需要写入的字符。
同时,需要注意的是,在往缓冲区写入数据或者是从缓冲区读取数据的时候,必须保证数据的同步,因此GetMsg和PutChar函数均被声明为synchronized,并在具体实现中采取措施实现数据的同步。
接下来是SerialBuffer的源代码展示:
package serial; /** * * This class implements the buffer area to store incoming data from the serial * port. * */ public class SerialBuffer { private String Content = ""; private String CurrentMsg, TempContent; private boolean available = false; private int LengthNeeded = 1; /** * * This function returns a string with a certain length from the incomin * messages. * * @param Length The length of the string to be returned. * */ public synchronized String GetMsg(int Length) { LengthNeeded = Length; notifyAll(); if (LengthNeeded > Content.length()) { available = false; while (available == false) { try { wait(); } catch (InterruptedException e) {} } } CurrentMsg = Content.substring(0, LengthNeeded); TempContent = Content.substring(LengthNeeded); Content = TempContent; LengthNeeded = 1; notifyAll(); return CurrentMsg; } /** * * This function stores a character captured from the serial port to the * buffer area. * * @param t The char value of the character to be stored. * */ public synchronized void PutChar(int c) { Character d = new Character((char) c); Content = Content.concat(d.toString()); if (LengthNeeded < Content.length()) { available = true; } notifyAll(); } }
上述内容就是关于java中SerialBuffer相关内容的概述了。如果你对java知识感兴趣,想要了解更多java基础和常见问题,敬请关注奇Q工具网。
推荐阅读: