线程同步(保证线程安全:没有锁的线程只能等)获取锁 释放锁 运行慢
public class ThreadDemo { //买门票例子
public static void main(String[] args) {
MyTicket mt= new MyTicket(); //创建任务 /MyTicket2
Thread t1 = new Thread(mt); //创建线程 执行同一个任务
Thread t2 = new Thread(mt); //查询安全 修改不安全
t1.start();
t2.start();
}
}
public class MyTicket implements Runnable{
private int ticket=100;
private Lock lock =new ReentrantLock();//创建Look接口实现对象
private Object obj=new Object();//锁对象 全局变量 线程共用一把锁
public void run() {
while(true){//线程带着锁对象(obj)走,走完把锁放回
synchronized(obj){//同步代码块 //lock.lock();//获取锁
if(ticket>0){ //其他线程拿不到锁 进不来
Thread.sleep(50); //点 try...catch
System.out.print(Thread.currentThread().getName())
System.out.println(+"剩"+ticket--);//先打印 后减一
}
} //同步代码块 //lock.unlock();//释放锁
}
}
}
//同步方法锁 任务类
public class MyTicket2 implements Runnable{
private int ticket=100; //static 静态变量
public synchronized void sile(){//同步方法锁对象(this) 例:StringBuffer
if(ticket>0){ //static 静态同步方法 锁对象(类名.class)本类对象
Thread.sleep(50); //当前类的字节码对象
System.out.println(Thread.currentThread().getName())
System.out.println(+"剩"+ticket--+"张");//先打印 后减一
}
}
public void run() {
while(true){ sile(); }
}
}
// 高并发(多人同时访问)解决:加服务器 项目拆分
死锁:(多线程之间的同步嵌套时,两个线程互相等待) 避免
public class MyLock {
public static final Object lockA = new Object();
public static final Object lockB = new Object();
}
public class DeadLock implements Runnable {
private int x=0;
public void run() {
while(true){
if (x%2 ==0) {
synchronized (MyLock.lockA) {
System.out.println("if-LockA");
synchronized (MyLock.lockB) {
System.out.println("if-LockB");
}
}
} else{
synchronized (MyLock.lockB) {
System.out.println("else-LockB");
synchronized (MyLock.lockA) {
System.out.println("else-LockA");
}
}
}
x++;
}
}
}
public class Demo01 {
public static void main(String[] args) {
DeadLock dl=new DeadLock();
Thread t0=new Thread(dl);
Thread t1=new Thread(dl);
t0.start();
t1.start();
}
}