How to properly synchronize Threads/Classes
Hello All! Thank you very much for viewing this thread. My problem is I am trying to pass a number value between classes/thread of the same java project in eclipse. I have a java project of 9 classes with three threads. The Display Class/Thread needs to accept a value coming from the Tcpdump Class/Thread. When both of these are ran separately everything is fine. But when I try to pass the count value in Tcpdump it does not function correctly. I am trying to understand synchronizing since I think that is my solution however I do not really know where to begin. I have posted the Tcpdump class below.
__________________________________________________
import java.io.IOException;
import jpcap.*;
import jpcap.packet.Packet;
public class Tcpdump extends Thread implements PacketReceiver{
static int index = 1;
public int received_packets;
//int count = 0;
public int count;
public int packetPSecond;
private Main classMain;
public int tcpdumpSecondCount;
NetworkInterface[] devices = JpcapCaptor.getDeviceList();
public Tcpdump(Main projectMain){
System.out.println("Tcpdump.Tcpdump()");
this.classMain = projectMain;
}
public void receivePacket(Packet packet) {
System.out.println("THIS IS THE PACKET NUMBER: " + " - " + packet);
countPackets();
}
public void countPackets() {
this.count = this.count + 1;
System.out.println("This is the value of count: " + count);
//This line passes count--which is the (Total Number of packets)
classMain.display.gettcpDumpPacketCount(count);
}
public void openDevice() {
System.out.println("This is Tcpdump Opendeive...packets should be captured now");
NetworkInterface[] devices = JpcapCaptor.getDeviceList();
JpcapCaptor jpcap = null;
System.out.println("usage: java Tcpdump <select a number from the following>");
try {
jpcap = JpcapCaptor.openDevice(devices[0], 2000, false, 1000);
//jpcap = JpcapCaptor.openDevice(devices[1], 2000, false, 1000);
} catch (IOException e) {
e.printStackTrace();
}
jpcap.loopPacket(-1, new Tcpdump(classMain));
jpcap.close();
}
public void run() {
System.out.println("Tcpdump is on--------------------------!!!");
openDevice();
}
public void main() throws Exception {
System.out.println("This is Tcpdump main, openDevice should start:");
}
}
__________________________________________________ __
The display method I am using to accept the value is
public void gettcpDumpPacketCount(int count){
System.out.println("THis is count at display: " + count);
dumpPacketCount = count;
}
__________________________________________________ __
Both classes and threads are initialized in my main class.
I would appreciate any advice you could give me. Thanks a lot.
Dan
|