所以我正在测试synchronized关键字.这是我尝试的一个例子:
public class MyTest {
static int i = 0;
public static void main(String[] args) {
new Thread(t1).start();
new Thread(t2).start();
}
private static void countMe(String name){
i++;
System.out.println("Current Counter is: " + i + ", updated by: " + name);
}
private static Runnable t1 = new Runnable() {
public void run() {
try{
for(int i=0; i<5; i++){
countMe("t1");
}
} catch (Exception e){}
}
};
private static Runnable t2 = new Runnable() {
public void run() { …Run Code Online (Sandbox Code Playgroud) 假设我有两个类,A和B.A类被定义为抽象,而B扩展了这个抽象类,最后我测试结果,两个类都是同一个包的一部分.
public abstract class A {
protected abstract void method1();
protected void method2() {
System.out.println("This is Class A's method");
}
}
public class B extends A {
@Override
protected void method1() {
System.out.println("This is B's implementaiton of A's method");
}
}
Run Code Online (Sandbox Code Playgroud)
现在当我测试它们时:
B b = new B();
b.method1();
b.method2();
Run Code Online (Sandbox Code Playgroud)
我得到预期的输出:
This is B's implementaiton of A's method
This is Class A's method
Run Code Online (Sandbox Code Playgroud)
问题:
@Override关键字的目的是什么,因为如果省略它,它仍然可以正常工作. method2()在B中实现.然后输出更改为B中使用的内容.这是否也会覆盖父类方法?那么在A类中将方法明确定义为抽象的目的是什么?我知道TreeSet以排序的方式存储对象.但有没有办法可以自定义订单?
例如,如果我有一个树集:
TreeSet t1 = new TreeSet();
t1.add("c");
t1.add("d");
t1.add("a");
Run Code Online (Sandbox Code Playgroud)
现在,如果我迭代它>
Iterator it1 =t1.iterator();
while(it1.hasNext()){
Object o1 = it1.next();
System.out.println(o1);
}
Run Code Online (Sandbox Code Playgroud)
我将永远得到订单:a>c>d,但是我希望它返回与我添加元素相同的订单,即c>d>a?