2006-08-23

多线程环境下访问同步方法

public class ThreadTest
{
static ThreadTest tt = new ThreadTest();
class Thread1 extends Thread
{
public void run()
{
while(true)
tt.read();
}
}

class Thread2 extends Thread
{
public void run()
{
while(true)
tt.write();
}
}

private int count;

public synchronized void read()
{
System.out.println("read " + count);
try
{
Thread.sleep(3000L);
} catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println("read " + count);
}

public synchronized void write()
{
System.out.println("write " + count++);
}

public static void main(String[] args)
{
ThreadTest test = new ThreadTest();
test.new Thread1().start();
test.new Thread2().start();
}
}
“锁”是指对象锁,没有“成员锁”或“函数锁”。访问一般函数(unsynchronized)时不用获取对象锁。访问同步函数时须获取函数所在对象的对象锁,这时其它同步函数、方法皆不可访问,而非同步的成员可以。

No comments: