用静态方法创建Java多线程
问题描述:
我完全不熟悉Java(但我对C++有一些知识),并且无法在现有主题上找到答案。用静态方法创建Java多线程
我有一个包含静态方法的公共类。这个创建了多个线程,每个线程都实例化这个类的一个实例,每个实例都有一个阻塞处理。
我尝试添加一个Runnable为这个类的一个领域,但我是一个有点困惑如何正确做...
public class MyClass extends java.awt.Frame {
String myString1;
String myString2;
String myString3;
private ActionListener aL;
private volatile boolean boolRunning;
public Runnable r = new Runnable(){
@Override
public void run() {
MyClass q = new MyClass(MyClass.this);
synchronized (this) {
MyClass.this.notify();
}
}
}
private MyClass(String toParse){
String[] parsed = toParse.split(":");
this.myString1 = parsed[0];
this.myString2 = parsed[1];
this.myString3 = parsed[2];
instantiateFrame();
}
public void instantiateFrame(){
this.setBounds(...);
this.setLayout(...);
Button btn = new Button("Submit");
[...]
this.aListener = new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
/************************/
/* Treatment hear */
/* Increment static Var */
/************************/
synchronized (MyClass.this){
boolRunning = true;
MyClass.this.notify();
}
MyClass.this.dispose();
}
};
btn.addActionListener(aL);
this.add(btn);
this.setVisible(true);
/* Wait for btn clicked */
/* Blocking method */
synchronized(this) {
try {
this.wait();
boolRunning = true;
} catch (InterruptedException ex) {
Logger.getLogger(MyClass.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public static int startThreads(String[] toParseTable){
Thread[] t = new Thread[toParseTable.length];
for (int i = 0; i < toParseTable.length; i++) {
t[i] = new Thread(MyClass.r); // Not compiling : Non static variable "r" cannot be referenced from a static context
t[i].start();
}
/* Wait for all Threads */
for (Thread th : t) {
try {
th.join();
} catch (InterruptedException ex) {
Logger.getLogger(MyClass.class.getName()).log(Level.SEVERE, null, ex);
}
}
return MyClass.someStaticVar;
}
public static void main(String[] args) {
String[] someStrings = {"...:...:...",
"...:...:...",
"...:...:..."};
try {
System.out.println(MyClass.startThreads(someStrings));
} catch (CustomThrownException e) {
System.err.println(e.getMessage());
}
}
}
答
您试图访问一个实例变量(即是一个属于一个对象的变量)在一个方法中不属于一个实例对象,而是属于这个类。 static
函数和变量是全局类,但不能访问实例中的变量,因为没有隐式this
。
class Foo {
private int value = 2;
private static int woz = 6;
public void foo() {
System.out.println(value); // ok, access instance variable in instance method with implicit this object
System.out.println(woz); // ok, access 'class global' variable
}
public static void bar() { // is a 'class' method, not an instance method
System.out.println(value); // can't because there is no 'this' object here
System.out.println(woz); // ok, access 'class global' variable
}
+0
我知道静态方法,但我无法看到如何以其他方式做到这一点! –
+0
根据我的经验,从来没有必要使用静态变量,除了在单例或常量中使用时。 –
你的问题,具体是什么?看看[问] – pvg
你的代码中有相当多的问题。我建议在尝试多线程之前了解更多关于Java的知识。 –