同步是指所有的线程不是一起进入到方法中执行,而是按照顺序一个一个进来
两种处理方法:同步代码块,同步方法
1. 同步代码块必须锁定对象,所以一般可以锁定当前对象:this
class MyThread implements Runnable{
public int ticket=10;
@Override
public void run() {
for(int i=0;i<20;i++){
synchronized(this){
if(this.ticket>0){
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+
" sell tickets= "+this.ticket--);
}
}
}
}
}
public class TestDemo {
public static void main(String[] args) {
MyThread mt = new MyThread();
new Thread(mt,"Thread A").start();
new Thread(mt,"Thread B").start();
new Thread(mt,"Thread C").start();;
}
}
2.同步方法:
class MyThread implements Runnable{
public int ticket=10;
@Override
public void run() {
for(int i=0;i<20;i++){
this.sale();
}
}
public synchronized void sale(){
if(this.ticket>0){
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+
" sell tickets= "+this.ticket--);
}
}
}
public class TestDemo {
public static void main(String[] args) {
MyThread mt = new MyThread();
new Thread(mt,"Thread A").start();
new Thread(mt,"Thread B").start();
new Thread(mt,"Thread C").start();;
}
}
同步虽然是数据安全操作,但效率特别的慢