存在同步问题的代码:
public class Demo1 implements Runnable{
private int count = 5;
/**
* @param args
*/
public static void main(String[] args) {
Demo1 demo =new Demo1();
Thread h1=new Thread(demo);
Thread h2=new Thread(demo);
Thread h3=new Thread(demo);
h1.start();
h2.start();
h3.start();
}
@Override
public void run() {
for(int i=0;i<10;++i){
if(count>0){
try{
Thread.sleep(1000);
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println(count--);
}
}
}
}
运行结果:
5
4
3
2
1
0
-1
上述结果,出现-1显然是不对的,这是由于在同一时间两个线程对count进行了操作导致的
引入同步代码块和同步方法来解决上述问题
【同步代码块】:
语法格式:
synchronized(同步对象){
//需要同步的代码
}
public void run() {for(int i=0;i<10;++i){
synchronized (this) {
if(count>0){
try{
Thread.sleep(1000);
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println(count--);
}
}
}
}
【同步方法】
语法格式为synchronized 方法返回类型方法名(参数列表){
// 其他代码
}
@Override
public void run() {
for(int i=0;i<10;++i){
count();
}
}
private synchronized void count(){
if(count>0){
try{
Thread.sleep(1000);
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println(count--);
}
}