内部类对象创建的问题

如下代码:

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

}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值