We're a community of 1.1M IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,080,514 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

How to run a non-static method in a thread

All,

How do I get the readSensor() method to run in threads?

Thread location1Thread;
Thread location2Thread;

Logger location1 = new Logger("187.20.150.20", 2000);
Logger location2 = new Logger("187.20.150.21", 2000);

// The next 2 lines lines result in the following error message:
// "An object reference is required for the non-static field, method, or property...
location1Thread = new Thread(location1.readSensor);
location2Thread = new Thread(location2.readSensor);

I don't know how to resolve the error. Can anyone help me with this?

Thanks,
Bill

3
Contributors
4
Replies
2 Days
Discussion Span
5 Months Ago
Last Updated
5
Views
WDrago
Junior Poster in Training
88 posts since Dec 2010
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

Try this:

location1Thread = new Thread(location1.readSensor());
location2Thread = new Thread(location2.readSensor());
tinstaafl
Nearly a Posting Virtuoso
1,476 posts since Jun 2010
Reputation Points: 429
Solved Threads: 262
Skill Endorsements: 14

Can't use parenthesis there, generates error: "Method name expected" with a red squiggly under location1.readSensor()

Currently the red squiggly is under location1Thread and location2Thread. With the error message noted in my original post.

Thanks anyway...

-Bill

WDrago
Junior Poster in Training
88 posts since Dec 2010
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

I solved this problem. The following lines have to be in main(), not in the class that contains main(). I don't understand why.

Thread location1Thread;
Thread location2Thread;

Anyone?

Thanks,
Bill

WDrago
Junior Poster in Training
88 posts since Dec 2010
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

The problem is that you were attempting to access a member variable from a static context (ie the Main method). You need to either use variables local to your static method or move the initialisation of the threads to the constructor and instantiate your class as an object first.

darkagn
Nearly a Posting Virtuoso
1,223 posts since Aug 2007
Reputation Points: 404
Solved Threads: 212
Skill Endorsements: 15

This article has been dead for over three months: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
 
© 2013 DaniWeb® LLC
Page generated in 0.3054 seconds using 2.66MB