Netbeans doesn't like Thread.yield()

When ever I try to use Thread.yield (in my vision thread), NetBeans complains with “invoking yield() on java.lang.Thread” (just a warning, not an error).

I’d prefer to have code with no warnings, and am concerned that I’m not doing this right.

Here’s the faulty class. Another class creates the thread object and calls start() on it.

package edu.wpi.first.wpilibj.templates;
import edu.wpi.first.wpilibj.camera.AxisCamera;
import edu.wpi.first.wpilibj.image.ColorImage;
import edu.wpi.first.wpilibj.image.BinaryImage;

public class Vision implements Runnable {
	AxisCamera    axis;
	ColorImage    colimage;
	MonoPosterize posterize;
	BinaryImage   binimage;
	Thread        thread;

	// Updates the target positions if a new image exists.
	public void refresh() {
		try {
			if (colimage != null) colimage.free();
			colimage = axis.getImage();
			if (binimage != null) binimage.free();
			binimage = posterize.posterize(colimage);
			System.out.println(binimage.getNumberParticles());
			System.out.println(binimage.getParticleAnalysisReport(0));

		} catch (Exception e) {
			System.out.println(e);
		}
	}
	
	private void WaitForImage() {
		while (!axis.freshImage()) {
			Thread.yield();
		}
	}
	
	// This is run by Thread.start();
	public void run() {
		thread = Thread.currentThread();
		thread.setPriority(Thread.MIN_PRIORITY);
	}
}

Can someone verify that I’m coding this correctly?

You are [coding it correctly]. Hit Alt+Enter on one of the Thread.yield() lines and turn the warning off.

NetBeans complains as Thread.yield() is sometimes used incorrectly. Instead of being used to prevent threads from starving (having one thread take most of the CPU time) like it should be, it can be used with varying degrees of effectiveness to make a statement look atomic (in one piece), e.g. have the thread yield before some operation, to (try to) keep it from being forced to yield in the middle of that operation (which could cause concurrency issues).

If you have to ask, don’t worry about it. If it really bugs you and you don’t want to just turn it off, you could make your thread sleep for an appropriate amount of time.

Thread.yield and Thread.sleep do different things. Thread.yield says to give others a turn. Thread.sleep says don’t even think about getting back to me for X milliseconds.

Yes, but when a thread sleeps the scheduler moves on to the next task. The greatest resolution you can expect is somewhat greater than a millisecond, more like sixteen (iirc) due to task switching (if it happens) and other threads running.

It’s probably true that sleeping for only a few ms is a bit slim… I would suggest something more like 50, if you can spare it. But this is only if he doesn’t want to turn off the warning that bugs him.

Then I’ll turn off that warning… I know how to use Thread.yield() (correctly) :slight_smile:

Thanks for the help.

EDIT: clarification