多线程使用同一个数据源的安全问题解决 三种方法:

package day08;
//第一种,使用synchronized代码块解决同步锁问题
public class StaticTongbuDemo implements Runnable {
private int taick = 100;
@Override
public void run() {
synchronized (this) {
while (true) {
if (taick > 0) {
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + “---->正在卖第” + taick + “张”);
taick–;
}
}
}
}
}
}
package day08;
//第二种:利用同步方法解决多线程之间同步锁问题
public class StaticTongbuDemo01 implements Runnable {
private int taick = 100;

@Override
public void run() {
    suoJie();
}
public synchronized void suoJie() {
    while (true) {
        if (taick > 0) {
                System.out.println(Thread.currentThread().getName() + "---->正在卖第" + taick + "张");
                taick--;

        }
    }
}

}
package day08;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
//第三种:使用Lock接口中的方法解决同步锁问题
public class StaticTongbuDemo02 implements Runnable {
private int taick = 100;
Lock l = new ReentrantLock();
@Override
public void run() {
while (true) {
l.lock();

        if (taick > 0) {
            try {
                Thread.sleep(1000);
                System.out.println(Thread.currentThread().getName() + "---->正在卖第" + taick + "张");
                taick--;
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                l.unlock();
            }
        }
    }

}

}
package day08;
//测试类:创建实现Runable接口的类对象
//创建线程,传入对象
//开启线程
public class StatictongbuText {
public static void main(String[] args) {
StaticTongbuDemo01 run = new StaticTongbuDemo01();
Thread t0 = new Thread(run);
Thread t1 = new Thread(run);
Thread t2 = new Thread(run);
t0.start();
t1.start();
t2.start();
}
}

你可能感兴趣的:(多线程使用同一个数据源的安全问题解决 三种方法:)