package com.data.entity;
import java.util.ArrayList;
import java.util.List;
public class MyList {
public List<Integer> list=new ArrayList<>();
//同步方法 线程锁
//public synchronized void insert(int i){
public void insert(int i){
list.add(i);
}
public void query(){
System.out.println("长度:"+list.size());
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}
}
import com.data.entity.MyList;
public class text8 {
public static void main(String[] args)throws Exception {
MyList m=new MyList();
Thread t1=new Thread(()->{
synchronized (m) { //同步代码块 线程琐
for (int i = 1; i <= 5; i++) {
m.insert(i);
}
}
});
Thread t2=new Thread(()->{
synchronized (m) { //同步代码块 线程琐
for (int i = 6; i <= 10; i++) {
m.insert(i);
}
}
});
t1.start();
t2.start();
t1.join();
t2.join();
m.query();
}
}
区别
-
同步方法: 线程执行需要同时争抢时间片和锁标记,写法简单但效率较慢
-
同步代码块: 线程只需要争抢时间片, 开启互斥锁的线程默认拥有锁标记, 效率较快但写法相对繁琐