今天在看一个多线程的问题时碰到了错误,源代码是:
package com.xyf.exercise;
/**
* 用继承方式启用两线程
* 一个输出26个英文字母,
* 一个输出1到26
* */
public class initial {
public char ch ;//输出的字符
public int j;//输出的数字
//线程1:输出26个字母
class Thread1 extends Thread{
public void run(){
for(int i=0;i<26;i++){
char ch = 'a';
System.out.println(Thread1.currentThread().getName());
System.out.println((char)(ch+i));
}
}
}
//线程2:输出1~26
class Thread2 extends Thread{
public void run(){
for(int i=0;i<26;i++){
int j = 1;
System.out.println(Thread1.currentThread().getName());
System.out.println(j+i);
}
}
}
//初始化的构造方法
public initial(char a,int j){
this.ch = a;
this.j = j;
}
public static void main(String[] args) {
Thread1 t1 = new Thread1();
Thread2 t2 = new Thread2();
t1.start();
t2.start();
}
}
然后报错:No enclosing instance of type initial is accessible. Must qualify the allocation with an enclosing instance of type initial (e.g. x.new A() where x is an instance of initial).
通过查阅资料后发现,我在Initial方法里定义的线程类Thread1和Thread2是内部类,而他们两个是动态的,而main方法是静态的,就好像在静态方法里面不能调用非静态的方法一样的。
此时有两种解决方法:
1.把这两个类定义为静态类:
//线程1:输出26个字母
static class Thread1 extends Thread{
public void run(){
for(int i=0;i<26;i++){
char ch = 'a';
System.out.println(Thread1.currentThread().getName());
System.out.println((char)(ch+i));
}
}
}
//线程2:输出1~26
static class Thread2 extends Thread{
public void run(){
for(int i=0;i<26;i++){
int j = 1;
System.out.println(Thread1.currentThread().getName());
System.out.println(j+i);
}
}
}
2.把这两个类放在initial类的外面:
package com.xyf.exercise;
/**
* 用继承方式启用两线程
* 一个输出26个英文字母,
* 一个输出1到26
* */
public class initial {
public char ch ;//输出的字符
public int j;//输出的数字
//初始化的构造方法
public initial(char a,int j){
this.ch = a;
this.j = j;
}
public static void main(String[] args) {
Thread1 t1 = new Thread1();
Thread2 t2 = new Thread2();
t1.start();
t2.start();
}
}
//线程1:输出26个字母
class Thread1 extends Thread{
public void run(){
for(int i=0;i<26;i++){
char ch = 'a';
System.out.println(Thread1.currentThread().getName());
System.out.println((char)(ch+i));
}
}
}
//线程2:输出1~26
class Thread2 extends Thread{
public void run(){
for(int i=0;i<26;i++){
int j = 1;
System.out.println(Thread1.currentThread().getName());
System.out.println(j+i);
}
}
}
补充知识:
1.内部类:
在Java中,可以将一个类定义在另一个类里面或者一个方法里面,这样的类称为内部类。广泛意义上的内部类一般来说包括这四种:成员内部类、局部内部类、匿名内部类和静态内部类。
2.多线程实现的三种方法:
1)继承Thread类,重写父类run()方法
2)实现runnable接口
3)使用ExecutorService、Callable、Future实现有返回结果的多线程(JDK5.0以后)