我正在尝试使用两个线程添加String值ArrayList.我想要的是,当一个线程添加值时,另一个线程不应该干扰,所以我使用了该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) 我有两个接口:
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()?
我现在有一个数组对象。该函数应返回一个包含所有对象值的数组的数组。错误在哪里?
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)