Java有许多进程同步的方法,其中synchronized关键字的使用比较简单。Java每个对象都有一个内部锁,用synchronized关键字直接修饰方法,可以在方法调用时自动上锁,在方法结束调用时自动解锁。
线程未同步示例
注意:Thread.sleep(x)线程延时方法一定要有,不然可能会因为程序执行太快看不到进程冲突,导致数字正常减小。
public class Main {
public static void main(String[] args) {
MyRunnable mr = new MyRunnable();
new Thread(mr).start();
new Thread(mr).start();
new Thread(mr).start();
}
}
class MyRunnable implements Runnable{
private int count = 100;
@Override
public void run(){
while( count > 0){
try{
Thread.sleep(50);
}catch (Exception e){
}
System.out.println(count--);
}
}
}
结果:
线程同步示例
将要同步的程序段(术语叫临界区)变成一个方法fun,并用关键字修饰,在原位置调用fun方法。
public class Main {
public static void main(String[] args) {
MyRunnable mr = new MyRunnable();
new Thread(mr).start();
new Thread(mr).start();
new Thread(mr).start();
}
}
class MyRunnable implements Runnable{
private int count = 100;
@Override
public void run(){
fun();
}
public synchronized void fun(){
while( count > 0){
try{
Thread.sleep(50);
}catch (Exception e){
}
System.out.println(count--);
}
}
}
结果: