synchronized:利用上锁实现数据同步,避免多线程操作的情况下,数据出现异常。
另一个线程必须等待当前线程执行完这个代码块以后才能执行该代码块。
一个线程获得了一个对象的同步锁,那这个对象上所有被同步的代码都不能执行,但不影响其他非同步代码。
在代码块前加上 synchronized关键字,则此代码块就成为同步代码块,
同步代码块:明确锁住对象
synchronized(同步对象){
需要同步的代码;
}
同步方法,跟同步代码块的功能类似:锁住的对象是this
public synchronized void fun1(){
...
}
实例:
class MyThread implements Runnable
{
int i = 100;
public void run(){
while(true){ //并不是锁止状态,t1,t2同时进入
System.out.println("-------------"+Thread.currentThread().getName());
synchronized(this){ //如t1锁住,就算t2抢到cpu也进不去
System.out.println(Thread.currentThread().getName() + i);
i--;
if(i<0){
break;
}
}
}
}
}
class Test
{
public static void main(String args[]){
MyThread myThread = new MyThread();
//生成两个Thread对象,共用一个线程体
Thread t1 = new Thread(myThread);
Thread t2 = new Thread(myThread);
t1.setName("线程a");
t2.setName("线程b");
t1.start();
t2.start();
}
}
来源:https://www.cnblogs.com/tinyphp/p/3759608.html