作者 主題: java 多執行緒哪裡錯了? (RS-232)  (閱讀 5153 次)

0 會員 與 1 訪客 正在閱讀本文。

FOXONE

  • 可愛的小學生
  • *
  • 文章數: 1
    • 檢視個人資料
java 多執行緒哪裡錯了? (RS-232)
« 於: 2008-05-14 12:16 »
import java.util.Date;
import java.util.Enumeration;
import java.util.TooManyListenersException;
import java.net.*;
import java.io.*;
import java.util.*;
import javax.comm.*;
 
public class cc123 {
int i,u;
  static CommPortIdentifier portId2;
  static Enumeration portList2;
  static String defaultPort = "COM1";
  static String messagein2;
  String messageinvalue;
  InputStream inputStream232;
  SerialPort serialPort2;
  Thread readThread;
 
  public cc123(){
new Thread( new time2()).start();
   }
   
class time2 implements Runnable, SerialPortEventListener
{
   
public void run(){
   while(true) {
   portList2 = CommPortIdentifier.getPortIdentifiers();
   while (portList2.hasMoreElements()) {
   portId2 = (CommPortIdentifier) portList2.nextElement();
   if (portId2.getPortType() == CommPortIdentifier.PORT_SERIAL) {
   if (portId2.getName().equals(defaultPort)) {
   @SuppressWarnings("unused")
   time2 reader = new time2();
   }
   }
   }   
   
   try {
   Thread.sleep(20000);
   } catch (InterruptedException e) {
     }
   }
       }
   public void serialEvent(SerialPortEvent event) {
   switch(event.getEventType()) {
   case SerialPortEvent.BI:
   case SerialPortEvent.OE:
   case SerialPortEvent.FE:
   case SerialPortEvent.PE:
   case SerialPortEvent.CD:
   case SerialPortEvent.CTS:
   case SerialPortEvent.DSR:
   case SerialPortEvent.RI:
   case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
   break;
   case SerialPortEvent.DATA_AVAILABLE:
   byte[] readBuffer = new byte[1];
   try {
   while (inputStream232.available() > 0) {
   int numBytes = inputStream232.read(readBuffer);
   }
   messagein2 = new String(readBuffer);
   //int intmessage=Integer.parseInt(messagein);   
   //System.out.print(intmessage);   
   System.out.print(messagein2);         
   } catch (IOException e) {}
   break;
   }
   }   
   
   public time2() {
   try {
   serialPort2 = (SerialPort) portId2.open("SimpleReadApp", 2000);
   } catch (PortInUseException e) {}   
   try {
     inputStream232 = serialPort2.getInputStream();
   } catch (IOException e) {}   
      try {
   serialPort2.addEventListener(this);
      } catch (TooManyListenersException e) {}     
   serialPort2.notifyOnDataAvailable(true);   
   try {
   serialPort2.setSerialPortParams(9600,
   SerialPort.DATABITS_8,
   SerialPort.STOPBITS_1,
   SerialPort.PARITY_NONE);
   } catch (UnsupportedCommOperationException e) {}   
   readThread = new Thread(this);
   readThread.start();
 
   while(true) {
   for(int i = 0;i < 50000000;i++);
   }
   }
  }   
 
  public static void main(String[] args) {
    new cc123();
  }
}