类部类创建对象

//Unresolved compilation problem:  No enclosing instance of type SynchronizedTest is accessible. Must qualify the allocation with an enclosing instance of type SynchronizedTest (e.g. x.new A() where x is an instance of SynchronizedTest).

今天在练习多线程同步的时候遇到了一个如上的问题 百度发现是因为内部类对象不可以直接通过new 类名()去创建 正确的创建方法是

外部类 外名称 = new 外部类类名()

内部类  内名称 =外名称.new 内部类类名()

源码:

package com.swust.thread;

public class SynchronizedTest {

private static int num;
public SynchronizedTest(int num) {
this.num = num;
}
//定义同步方法
private final static synchronized void doit() {
if(num>0) {
try {
Thread.sleep(1000);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
System.out.println("tickets:"+(num--));
}
}

public class Mythread implements Runnable{
@Override
public void run() {
while(true) {
doit();
}
}
}

public static void main(String[] args) {
SynchronizedTest test = new SynchronizedTest(10);
Mythread mythread = test.new Mythread();
Thread threadOne = new Thread(mythread);
Thread threadTwo = new Thread(mythread);
threadOne.start();
threadTwo.start();
}
}

猜你喜欢

转载自www.cnblogs.com/walxt/p/12365243.html