# MultiThread 多線程 (Java) ###### tags: `java` `MultiThread` ## Intro >使用於較花時間的演算,而且可以在背景執行(例如: 不用即時顯示再螢幕) EX: **Decode** > **∈ 並發 OR multiTasking** > ![](https://i.imgur.com/7wVhuV1.png) **(Inside a core)** ## Example Code ### Decode QR code ```java class multiDecode implements Runnable { private Bitmap bm; private int no; public multiDecode(Bitmap temp,int idx) { bm = temp; no = idx; } private String _value = null; public void run() { String TAG = "getQR"; while(_value == null){ _value = QRcodeScanner.decodeQRImage(bm); if (_value != null && _value.length() > 1) { try{ Thread.sleep(1000); //modified sleeping time } catch (Exception e){ Log.d(TAG, e.getMessage()); } api.judgeSendDiscoveredQR(no, _value); try{ Thread.sleep(1000); // modified sleeping time } catch (Exception e){ Log.d(TAG, e.getMessage()); } String str; str = _value.replaceAll("[^-0-9.]", ""); double val = Double.parseDouble(str); Log.d(TAG, "\n\nQRno="+no+"string="+_value+"val= "+val+"iterate times="+"\n\n"); p3[no] = val; break; } } } } ``` ### Decode Input Data from Port ```java class LidarListener implements Runnable { private SerialPort _port; private LidarProxy _proxy; public LidarListener(LidarProxy proxy, SerialPort.Port port) { _proxy = proxy; _port = new SerialPort(115200, port); } public void run() { while (true) { try { byte[] read = _port.read(9); _proxy.lastReadDistance = read[2] & 0xFF; } catch (Exception e) { DriverStation.reportError("LidarListener exception: " + e.toString(), false); } } } } ```