Pengiuns Pengiuns - 4 months ago 16
Java Question

Unable to access method of thread class?

Newb here so apologies

public class Threads implements Runnable{
public String threadName;
private volatile boolean running = true;

public Threads( String name){
threadName = name;
}

public void setoff(){
running = false; //this.running = false;
}

public void seton(){
running = true; //this.running = true;
}

public void run() {
while(this.running){
System.out.println("running");
}
if(this.running ==false){
System.out.println("stopped");
}
System.out.println("Thread " + threadName + " exiting.");
}


}


--end class

public class MainFrame extends javax.swing.JFrame {
Thread R1 = null;
public MainFrame() {
initComponents();
}

private void jbtnstartActionPerformed(java.awt.event.ActionEvent evt) {
R1 = new Thread(new Threads("Thread 1"));
R1.start();
}
}


I'm unable to call any functions of R1 from my main class? (seton(), setoff() etc etc)

Any help would be greatly appreciated.

Answer

You can't call any methods of your Threads class, because you don't have a reference to the object of that type.

Change your code to:

Threads R1 = new Threads("Thread 1");
Thread thread = new Thread(R1);
thread.start();

Thread.sleep(1000);
R1.setoff();

Also, if(this.running ==false) should be written if (! this.running).

Or better yet, that line should be removed. The only way for that line to be executed, is for the preceding while loop to exit, which only happens when this.running is false, so the test in the if statement is redundant.