1.线程同步
并发:同一对象被多个线程同时操作
线程同步安全性:队列+锁
package com.atguigu.demo05;
import java.util.ArrayList;
import java.util.List;
public class TestList {
public static void main(String[] args) {
final List<String> list=new ArrayList<String>();
for (int i = 0; i < 10000; i++) {
new Thread(()->{
synchronized (list){
list.add(Thread.currentThread().getName());
}
}).start();
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}
测试JUC安全类型的集合:
package com.atguigu.demo05;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
public class TestList {
public static void main(String[] args) {
CopyOnWriteArrayList<String> list=new CopyOnWriteArrayList<String>();
for (int i = 0; i < 10000; i++) {
new Thread(()->{
list.add(Thread.currentThread().getName());
}).start();
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}
2.死锁
死锁:多个线程各自占有一些共享资源,并且互相等待其他线程占有的资源才能运行,而导致两个或者多个线程都在等待对方释放资源,都停止执行的情形,某一个同步块同时拥有“两个以上对象”的锁时,就可能会发送“死锁”问题。
解决死锁问题:
package com.atguigu.demo06;
public class TestLock {
public static void main(String[] args) {
MakeUp makeUp1=new MakeUp(0,"灰姑娘");
MakeUp makeUp2=new MakeUp(1,"白雪公主");
new Thread(makeUp1).start();
new Thread(makeUp2).start();
}
}
class Mirro{
}
class LipsLick{
}
class MakeUp implements Runnable{
static LipsLick lipsLick=new LipsLick();//口红对象
static Mirro mirro=new Mirro();
int chioce;
String girlName;
public MakeUp(int chioce, String girlName) {
this.chioce = chioce;
this.girlName = girlName;
}
@Override
public void run() {
if(chioce==0){
synchronized (lipsLick){
System.out.println(this.girlName+"口红");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
synchronized (mirro){
System.out.println(this.girlName+"镜子");
}
}else{
synchronized (mirro){
System.out.println(this.girlName+"镜子");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
synchronized (lipsLick){
System.out.println(this.girlName+"口红");
}
}
}
}
3.lock锁
package com.atguigu.demo06;
import java.util.concurrent.locks.ReentrantLock;
//测试可重入锁
public class TestLock2 {
public static void main(String[] args) {
MyLock myLock=new MyLock();
new Thread(myLock,"小米").start();
new Thread(myLock,"华为").start();
new Thread(myLock,"京东").start();
new Thread(myLock,"腾讯").start();
}
}
class MyLock implements Runnable{
int tickets=10;
private final ReentrantLock lock=new ReentrantLock();
@Override
public void run() {
while (true){
try {
lock.lock();
if(tickets>0){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"拿到票了..."+tickets--);
}else {
break;
}
}finally {
lock.unlock();
}
}
}
}
synchronized与Lock对比: