Threadz中的数据安全问题解决方法
同步代码块
锁住多条语句操作共享数据
- 格式
synchronized(任意对象){
…
} - 实例
public class SellTickest implements Runnable{
private int tickets=100;
private Object obj=new Object();
public void run(){
while(true){
synchronized(obj){
if(tickets>0)){
try{
Thread.sleep(100);
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"正在卖第"+tickets+"张票");
}
}
}
}
同步
同步方法
将同步代码块单独放在一个方法中,但是把同步锁放在方法声明中
同步方法锁对象是this
private synchronized void sellTicket(){
if(tickets>0)){
try{
Thread.sleep(100);
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"正在卖第"+tickets+"张票");
}
}
同步静态方法
静态方法的内容是和类相关的,此时同步的内容要用
synchronized(sellTicket.class)
private static synchronized void sellTicket(){
if(tickets>0)){
try{
Thread.sleep(100);
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"正在卖第"+tickets+"张票");
}
}
线程安全的类
以下的类均实现了线程安全
- StringBuffer/StringBulider
接口下的方法都是synchronized同步方法 - Vector
接口下的方法都是synchronized同步方法 - Hashtable
接口下的方法都是synchronized同步方法
Lock的实现与释放
Lock实现提供比使用synchronized
- lock()
- unlock()
```java
public class SellTickest implements Runnable{
private int tickets=100;
private Lock lock=new ReentrantLock();
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+"张票");
tickets--;
}
}finally{
lock.unlock;
}
}
}
生产者消费者模式
Object中等待和唤醒方法
-
wait()导致当前线程等待,知道另一个线程调用该对象的notify()方法或notifyAll()方法
-
notify()唤醒正在等待对象监视器的单个线程
-
notifyAll()唤醒正在等待监视器的所有线程