多线程之间实现同步
public class Demo1 implements Runnable{
private int count=100;
@Override
public void run() {
while(count>0){
try {
sal();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void sal() throws InterruptedException{
Thread.sleep(100);
//synchronized (this) {
if(count>0){
System.err.println(Thread.currentThread().getName()+"第"+(100-count+1)+"张");
count--;
}
//}
}

问题引出:当多个线程同时访问同一个全局变量或者静态变量做读写操作时,可能会出现数据读取冲突问题,这就是线程安全问题。
解决办法:使用多线程之间同步synchronized。将可能会发生数据冲突问题(线程不安全问题)的使用synchronized包裹起来,只能让当前线程执行完成以后才释放锁。其他线程运行到这段代码以后以此类推,这次才能保证线程安全问题。
同步代码块
synchronized(对象)//这个对象可以为任意对象 ,比如,this关键字,字符串,
{
需要被同步的代码
}
代码示例
public class Demo1 implements Runnable{
private int count=100;
@Override
public void run() {
while(count>0){
try {
sal();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void sal() throws InterruptedException{
Thread.sleep(100);
synchronized (this) {
if(count>0){
System.err.println(Thread.currentThread().getName()+"第"+(100-count+1)+"张");
count--;
}
}
}
}

小结
同步的前提:
1,必须要有两个或者两个以上的线程
2,必须是多个线程使用同一个锁
必须保证同步中只能有一个线程在运行
好处:解决了多线程的安全问题
弊端:多个线程需要判断锁,较为消耗资源、抢锁的资源。
同步函数:在方法上修饰synchronized 称为同步函数(使用this锁)
public class Demo1 implements Runnable{
private int count=100;
@Override
public void run() {
while(count>0){
try {
Thread.sleep(100);
sal();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public synchronized void sal(){
if(count>0){
System.err.println(Thread.currentThread().getName()+"第"+(100-count+1)+"张");
count--;
}
}
静态同步函数
方法上加上static关键字,使用synchronized 关键字修饰 或者使用类.class文件。
静态的同步函数使用的锁是 该函数所属字节码文件对象
总结:
synchronized 修饰方法使用锁是当前this锁。
synchronized 修饰静态方法使用锁是当前类的字节码文件
多线程死锁:同步中嵌套同步,导致锁无法释放
Volatile
Volatile 关键字的作用是变量在多个线程之间可见。

浙公网安备 33010602011771号