一,多线程数据安全问题
当满足以下条件是就会出现多线程数据安全问题
1、是多线程环境
2、有共享数据
3、多条语句操作共享数据
二,同步代码块
格式:
synchronized(任意对象){
多条语句操作共享数据的代码;
}
优点:它解决了数据的安全问题。
缺点:每个线程都会去判断同步上的锁,很耗费资源,降低了程序的运行效率
三,同步方法
1、同步普通方法:
同步方法就是把synchronized关键字加到方法上
格式:修饰符 synchronized 返回值类型 方法名(方法参数){}
同步方法的锁对象是:this
2、同步静态方法
格式:修饰符 static synchronized 返回值类型 方法名(方法参数){}
同步静态方法的锁对象是:类名.class
对于这次的学习内容做的练习,卖票......
MyThread类
public class MyThread implements Runnable{
private int number=100;
Object obj=new Object();
@Override
public void run() {
while(true){
if(number%10==0){
// 没有用同步方法
// synchronized (obj){
// 用普通同步方法,注意如果这里用的不是this那这里的跟下面同步的方法的锁就不一样了,就无法解决数据安全问题了
synchronized (this){
// 同步静态方法,这个同理
// synchronized (MyThread.class){
if(number>0){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.print(Thread.currentThread().getName()+"卖出一张票,还剩下"+(number-1)+"张票。");
System.out.println("您是整数位客人,有免单特权");
number--;
}
}
}else{
sellTicket();
}
}
}
private synchronized void sellTicket() {
if(number>0){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"卖出一张票,还剩下"+(number-1)+"张票。");
number--;
}
}
}
测试类
public class ThreadTest {
public static void main(String[] args) {
MyThread my=new MyThread();
Thread thread1=new Thread(my,"窗口1");
Thread thread2=new Thread(my,"窗口2");
Thread thread3=new Thread(my,"窗口3");
thread1.start();
thread2.start();
thread3.start();
}
}