同步代码块
package ThraadSave;
public class demo01piao {
public static void main(String[] args) {
RunableImpl run=new RunableImpl();
// 创建Thread类对象 构造方法中传递 Runable接口的实现类对象
Thread t0=new Thread(run);
Thread t1=new Thread(run);
Thread t2=new Thread(run);
t0.start();
t1.start();
t2.start();
}
}
package ThraadSave;
/*
* 同步代码块
* synchronized(锁对象){
* 可能会出现线程问题的代码 访问了共享数据的代码
* }
* 锁对象可以把同步代码块锁定 只让一个=线程在同步代码块中执行
* */
public class RunableImpl implements Runnable {
private int piao=100;
//创建一个锁对象
Object obj=new Object();
@Override
public void run() {
while(piao>0){
synchronized (obj){
if (piao>0){
//存在票 买票
try{
Thread.sleep(10);
}catch (InterruptedException e){
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"--->正在卖第"+piao--+"张票");
}
}
}
}
}
同步方法和静态同步方法
静态同步方法中用到的锁对象是本类的class属性 (class文件对象)
package ThraadSave;
public class demo02piao {
public static void main(String[] args) {
RunableImpl_1 run=new RunableImpl_1();
// 创建Thread类对象 构造方法中传递 Runable接口的实现类对象
Thread t0=new Thread(run);
Thread t1=new Thread(run);
Thread t2=new Thread(run);
t0.start();
t1.start();
t2.start();
}
}
package ThraadSave;
public class RunableImpl_1 implements Runnable {
private static int piao=100;
//创建一个锁对象
Object obj=new Object();
@Override
public void run() {
payPiao();
}
//静态方法 优先于对象 静态方法的锁对象是本类的class属性 -->class文件对象
public static synchronized void payPiao(){
//synchronized (RunableImpl_1.class){
while(piao>0){
if (piao>0){
//存在票 买票
try{
Thread.sleep(10);
}catch (InterruptedException e){
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"--->正在卖第"+piao--+"张票");
}
}
//}
}
}
lock锁
package ThraadSave;
public class demo03piao {
public static void main(String[] args) {
RunableImpl_2 run=new RunableImpl_2();
// 创建Thread类对象 构造方法中传递 Runable接口的实现类对象
Thread t0=new Thread(run);
Thread t1=new Thread(run);
Thread t2=new Thread(run);
t0.start();
t1.start();
t2.start();
}
}
package ThraadSave;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/*
* 使用lock锁
* lock接口中的方法 lock() unlock()
*
* 使用步骤
* Reentrantlock 实现lock接口
*
* 使用步骤:
* 1,在成员位置创建一个Reenrantlock对象
* 2,在可能会出现的代码前调用lock接口中的方法lock获取锁
* 3,在代码后调用unlock()*/
public class RunableImpl_2 implements Runnable {
private static int piao=100;
Lock l=new ReentrantLock();
@Override
public void run() {
payPiao();
}
public void payPiao() {
while(piao>0){
l.lock();
if (piao>0){
//存在票 买票
try{
Thread.sleep(10);
System.out.println(Thread.currentThread().getName()+"--->正在卖第"+piao--+"张票");
}catch (InterruptedException e){
e.printStackTrace();
}finally {
l.unlock();
}
}
}
}
}