无法访问线程类的方法?

时间:2016-07-17 04:59:40

标签: java multithreading

Newb在这里道歉

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.");
  }
}

- 结束课

 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();
}       
}

我无法从我的班级调用R1的任何功能? (seton(),setoff()等等)

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

您无法调用Threads类的任何方法,因为您没有对该类型对象的引用。

将您的代码更改为:

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

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

此外,if(this.running ==false)应写为if (! this.running)

或者更好的是,该行应该删除。要执行该行的方式是针对前面的while循环退出,这仅在this.running为假时发生,因此{{1}中的测试语句是多余的。

答案 1 :(得分:0)

没关系,让它继续工作;

Threads mythread = new Threads("222");
Thread R1 = new Thread(mythread);
mythread.seton();
R1.start();