zoukankan      html  css  js  c++  java
  • 类部类创建对象

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

  • 相关阅读:
    orm添加表记录
    创建多表模型
    包的使用
    日志写法
    os模块,是通过和操作系统交互进行操作
    sys python解释器做交互
    软件开发规范
    模块 time模块 datatime模块 random模块
    装饰器
    装饰器进阶
  • 原文地址:https://www.cnblogs.com/walxt/p/12365243.html
Copyright © 2011-2022 走看看