如下代码:
package com.interruptthread.project.interruptthread;
public class ReetrantThread {
public synchronized void OperaA(){
try {
OperaB();
System.out.println("执行操作A");
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public synchronized void OperaB() {
System.out.println("执行操作B");
}
public static void main(String[] args) {
ReetrantThread read = new ReetrantThread();
ThreadRun run1 = new ThreadRun();
ThreadRun run2 = new ThreadRun();
Thread thread1 = new Thread(run1);
Thread thread2 = new Thread(run2);
thread1.start();
thread2.start();
}
private class ThreadRun implements Runnable{
public void run() {
OperaA();
}
}
}
代码中红色的两行会出现问题:
No enclosing instance of type ReetrantThread is accessible. Must qualify the allocation with an enclosing instance of type ReetrantThread (e.g. x.new A() where x is an instance of ReetrantThread).
这个错误的意思是内部类对象的创建需要建立在外部类对象上,也就是说只有外部类对象创建了才能进行内部类对象创建(当然有一个例外,就是内部类是一个静态内部类)。
也就是说上面红色代码应该改成:
ThreadRun run1 = read.new ThreadRun();
ThreadRun run2 = read.new ThreadRun();
当然还可以将内部类移出到外部类的外面,单独做一个类,例如:
public class ReetrantThread {
public synchronized void OperaA(){
try {
OperaB();
System.out.println("执行操作A");
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public synchronized void OperaB() {
System.out.println("执行操作B");
}
public static void main(String[] args) {
ReetrantThread read = new ReetrantThread();
ThreadRun run1 = new ThreadRun(read);
ThreadRun run2 = new ThreadRun(read);
Thread thread1 = new Thread(run1);
Thread thread2 = new Thread(run2);
thread1.start();
thread2.start();
}
}
class ThreadRun implements Runnable{
ReetrantThread read = null;
public ThreadRun(ReetrantThread read) {
this.read = read;
}
public void run() {
read.OperaA();
}
}
还有一种方案,上面已经提过,就是将内部类改成静态的,代码如下:
public class ReetrantThread {
public synchronized void OperaA(){try {
OperaB();
System.out.println("执行操作A");
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public synchronized void OperaB() {
System.out.println("执行操作B");
}
public static void main(String[] args) {
ReetrantThread read = new ReetrantThread();
ThreadRun run1 = new ThreadRun(read);
ThreadRun run2 = new ThreadRun(read);
Thread thread1 = new Thread(run1);
Thread thread2 = new Thread(run2);
thread1.start();
thread2.start();
}
private static class ThreadRun implements Runnable{
ReetrantThread read = null;
public ThreadRun(ReetrantThread read) {
this.read = read;
}
public void run() {
read.OperaA();
}
}
}