Java多线程互斥访问比较简单,在方法前面加上synchronize修饰则变为同步方法。下面是例子:
class WorkThread extends Thread{
private CourruptedData data = null ;
private int type = 0 ;
public WorkThread(CourruptedData _data,int _type){
data = _data ;
type = _type ;
super.start();
}
public void run(){
data.performWork(type);
}
}
public class CourruptedData {
protected static int display = 1 ;
protected static int change = 2 ;
private WorkThread slowWorker = null ;
private WorkThread fastWorker = null ;
private int number = 0 ;
public CourruptedData() {
number = 1 ;
slowWorker = new WorkThread(this,display);//-----------慢进程先启动;
fastWorker = new WorkThread(this,change);
}
/*
* 关键字为synchronized时,方法修饰为同步方法,
* 慢线程调用performWokr()时,休眠两秒;
* 此时,不允许第二个线程打断第一个线程;
* 等第一个线程执行完毕之后,第二个线程才能将number改为-1;
*/
public synchronized void performWork(int type){
if (type == display)
{
System.out.println("Number before sleeping:" + number);
try{
slowWorker.sleep(2000);
}catch (InterruptedException ie){
System.out.println("Error : "+ie);
}
System.out.println("Number after working up:"+ number);
}
if (type == change)
number = -1 ;
}
public static void main(String args[])
{
CourruptedData test = new CourruptedData();
}
}
程序运行结果为:
当去掉performWork()方法的 synchronized 修饰之后,程序运行结果为: