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

  • 相关阅读:
    Docker pull镜像过慢解决方法
    BUUCTF pwn一分题目
    SROP例题
    2020 NUPCTF pwn题目
    BJD4th pwn pi
    0RAYS元旦招新赛
    exit_hook在pwn题中的应用
    eclipse导包导不进来
    java算法题每日一练01,java入门简单算法题小练
    解决chrome无法启用印象笔记-剪藏功能
  • 原文地址:https://www.cnblogs.com/walxt/p/12365243.html
Copyright © 2011-2022 走看看