小编Ful*_*Guy的帖子

Collections.synchronizedList()方法有什么用?它似乎没有同步列表

我正在尝试使用两个线程添加StringArrayList.我想要的是,当一个线程添加值时,另一个线程不应该干扰,所以我使用了该Collections.synchronizedList方法.但似乎如果我没有在对象上显式同步,则以不同步的方式完成添加.

没有显式同步块:

public class SynTest {
    public static void main(String []args){
        final List<String> list=new ArrayList<String>();
        final List<String> synList=Collections.synchronizedList(list);
        final Object o=new Object();
        Thread tOne=new Thread(new Runnable(){

            @Override
            public void run() {
                //synchronized(o){
                for(int i=0;i<100;i++){
                    System.out.println(synList.add("add one"+i)+ " one");
                }
                //}
            }

        });

        Thread tTwo=new Thread(new Runnable(){

            @Override
            public void run() {
                //synchronized(o){
                for(int i=0;i<100;i++){
                    System.out.println(synList.add("add two"+i)+" two");
                }
                //}
            }

        });
        tOne.start();
        tTwo.start();
    }
}
Run Code Online (Sandbox Code Playgroud)

我得到的输出是:

true one
true two
true one
true two …
Run Code Online (Sandbox Code Playgroud)

java collections multithreading synchronization

20
推荐指数
3
解决办法
2万
查看次数

两个接口中具有相同签名但返回类型不同的方法

我有两个接口:

interface S {
    public String m1();
}

interface O {
    public Object m1();
}
Run Code Online (Sandbox Code Playgroud)

我决定在类Test中实现O和S:

class Test implements O, S {

}
Run Code Online (Sandbox Code Playgroud)

我的问题 :

为什么我必须只实现方法public String m1()而不是其他方法?其次,为什么我不能实现public Object m1()而不是public String m1()

java

5
推荐指数
1
解决办法
347
查看次数

如何将数组对象转换为数组数组?

我现在有一个数组对象。该函数应返回一个包含所有对象值的数组的数组。错误在哪里?

const car = [
  {  
    "name":"BMW",
    "price":"55 000",
    "country":"Germany",
    "security":"Hight"
  },
  {  
    "name":"Mitsubishi",
    "price":"93 000", 
    "constructor":"Bar John",
    "door":"3",
    "country":"Japan",
  },
  {  
    "name":"Mercedes-benz",
    "price":"63 000", 
    "country":"Germany",
    "security":"Hight"
  }
 ];

function cars(car){
  return car.map(function(key) {
    return [[key]];
  });
}
console.log(cars(car));
Run Code Online (Sandbox Code Playgroud)

javascript arrays methods

0
推荐指数
1
解决办法
68
查看次数