无法获取存储在Java线程本地对象中的变量的整数值

时间:2016-02-09 01:15:51

标签: java multithreading thread-local

我试图获取线程局部对象的整数值,如下面的代码,但它不断抛出错误。但是,当我尝试将其显示为字符串时,它会显示。

我的问题:如何实现提取整数值?

注意:解析下面代码中的字符串不起作用

package ids;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Random;
import javax.swing.SwingWorker;
import jpcap.*;
import jpcap.packet.Packet;


public class InterfaceThread implements Runnable {

ThreadLocal MyInterfaceNumber = new ThreadLocal();

InterfaceThread() {

}

InterfaceThread(int InterfaceNumber) {
    MyInterfaceNumber.set(InterfaceNumber);
    System.out.println("Check: " + MyInterfaceNumber.get());
}

@Override
public void run() {
    String IntNum = (String) MyInterfaceNumber.get();

    int InterfaceToPrint = Integer.parseInt(IntNum);
    System.out.println("Interface: " + InterfaceToPrint);
    Messages msg = new Messages();
    Printer print = new Printer();

    try {

//Open Selected Interface     
        JpcapCaptor captor =         JpcapCaptor.openDevice(IDS.Interfaces[InterfaceToPrint], 65535, true, 5000);
        System.out.println("Interface Dlink Name: " + IDS.Interfaces[InterfaceToPrint].description);
        //  print.TextAreaAppend("Traffic on Interface "+InterfaceToPrint+" Now Being Sniffed\n");
        while (MainFrame.StopSniffing == false) {
            captor.processPacket(-1, new Printer());
        }
        //captor.loopPacket(-1, new Printer());
        captor.close();

    } catch (IOException ex) {
              msg.ErrorMessages("Interface " + InterfaceToPrint + " Encountered    Error: " + ex);
    }

}

public void Start(int InterfaceNumber) {

    InterfaceThread interfaceT = new InterfaceThread(InterfaceNumber);

    Thread thread = new Thread(interfaceT);

    thread.start();

  }

}

1 个答案:

答案 0 :(得分:1)

我建议您使用泛型来简化代码

private final ThreadLocal<Integer> int = new ThreadLocal<>();

// to read
Integer i = int.get();

// to write
int.set(i);