java 代码块,static,synchronized,内部类等问题

迅雷的笔试题,最后的一道30分的判断题,是代码块,static,synchronized,内部类的一道综合题。

一。代码块

1.普通代码块

2.构造代码块 优先于构造方法执行

3.静态代码块 优先于main函数,构造方法执行,且只执行一次

4.同步代码块

二。static

1.静态方法,静态变量都属于类。

2.调用都是通过类名引用。

3.静态方法不能使用非静态变量或方法。反之可以。

4.静态变量在内存中只有一份拷贝。

5.一种static特殊情况,内部静态类。 详见内部类。

三。内部类

一般情况:

1.内部类中隐含有外部类的引用。所以可以使用外部类中所有的东西。

2.创建内部类对象时,必须与外围类对象相关联,创建外围类对象之前,不可能创建内部类的对象。

特殊情况:静态内部类(也称嵌套类)

1.创建静态内部类是不需要外部类。

2.静态内部类不能访问外部类的非静态成员。

四。synchronized

定义:它用来修饰一个方法或者一个代码块的时候,能够保证在同一时刻最多只有一个线程执行该段代码。

    1) public Synchronized void method1 : 锁住的是该对象,类的其中一个实例 , 当该对象(仅仅是这一个对象)在不同线程中执行这个同步方法时,线程之间会形成互斥.达到同步效果,但如果不同线程同时对该类的不同对象执行这个同步方法时,则线程之间不会形成互斥,因为他们拥有的是不同的锁.
    2) Synchronized(this){ //TODO } 同一

    3) public Synchronized static void method3 : 锁住的是该类,当所有该类的对象(多个对象)在不同线程中调用这个static 同步方法时,线程之间会形成互斥,达到同步效果 , 但如果多个线程同时调用method1 , method3,则不会引互斥,具体讲看最后讲解.
    4) Synchronized(Test.class){ //TODO} 同三

    5) synchronized(o) {} 这里面的o可以是一个任何Object对象或数组,并不一定是它本身对象或者类,谁拥有o这个锁,谁就能够操作该块程序代码.

这里面1) 与2) 是线程安全的,但1)与3) , 2)与3) 他们所拥有的锁不一样,故不是同步的,不是线程安全的.

补充一道代码块,static 综合的题目

class Value {
    static int c = 0;
 
    Value() {
       c = 15;
    }
 
    Value(int i) {
       c = i;
    }
 
    static void inc() {
       c++;
    }
}
 
class Count {
    public static void prt(String s) {
       System.out.println(s);
    }
 
    Value v = new Value(10);
 
    static Value v1, v2;
    static {
       prt("in the static block of calss Count v1.c=" + v1.c + "  v2.c="
              + v2.c);
       v1 = new Value(27);
       prt("in the static block of calss Count v1.c=" + v1.c + "  v2.c="
              + v2.c);
       v2 = new Value();
       prt("in the static block of calss Count v1.c=" + v1.c + "  v2.c="
              + v2.c);
    }
}
 
public class TStaticBlock {
    public static void main(String[] args) {
       Count ct = new Count();
       Count.prt("in the main:");
       Count.prt("ct.c=" + ct.v.c);                       
       Count.prt("v1.c=" + Count.v1.c + "  v2.c=" + Count.v2.c);
       Count.v1.inc();
       Count.prt("v1.c=" + Count.v1.c + "  v2.c=" + Count.v2.c);
       Count.prt("ct.c=" + ct.v.c);
    }
}
结果:
in the static block of calss Count v1.c=0  v2.c=0
in the static block of calss Count v1.c=27  v2.c=27
in the static block of calss Count v1.c=15  v2.c=15
in the main:
ct.c=10
v1.c=10  v2.c=10
v1.c=11  v2.c=11
ct.c=11
原文地址:https://www.cnblogs.com/23lalala/p/2724061.html