接下来,我们对类TestInstance换一种访问方式:
例II:
(1)我们把类TestInstance的两个实例分别放在不同的线程当中
public class ForSynchronizedTwo {
public static void main(String ars[])throws IOException
{
RunInstance t = new RunInstance();
RunInstance y = new RunInstance();
Thread t1 = new Thread(t);
Thread y1 = new Thread(y);
t1.start();
y1.start();
}
}
class RunInstance implements Runnable{
TestInstance theinstance=new TestInstance();
public void run(){
theinstance.runtest();
}
}
(2)结果我们发现,两个线程用的都是m1这个方法,因为这时flag是个局部变量,它被创建了两次,
且并不会被线程互相访问,但是count 则不然,它是全局(严格说是static )变量,并且用了synchronized进行同步访问。
另外,请注意count = 2被打印两次,是因为Thread-0实行了 count++后,CPU等待Thread-1实行 count++
的结果。
Thread-0: m1's printing : count = 2
Thread-1: m1's printing : count = 2
Thread-0: m1's printing : count = 3
Thread-1: m1's printing : count = 4
Thread-0: m1's printing : count = 5
Thread-1: m1's printing : count = 6
Thread-0: m1's printing : count = 7
Thread-1: m1's printing : count = 8
Thread-0: m1's printing : count = 9
Thread-1: m1's printing : count = 10
Thread-0: m1's printing : count = 11
Thread-0: m1's printing : count = 13
Thread-1: m1's printing : count = 13
Thread-0: m1's printing : count = 14
Thread-1: m1's printing : count = 15
Thread-0: m1's printing : count = 16
Thread-1: m1's printing : count = 17
Thread-0: m1's printing : count = 18
Thread-1: m1's printing : count = 19
Thread-1: m1's printing : count = 20
例II:
(1)我们把类TestInstance的两个实例分别放在不同的线程当中
public class ForSynchronizedTwo {
public static void main(String ars[])throws IOException
{
RunInstance t = new RunInstance();
RunInstance y = new RunInstance();
Thread t1 = new Thread(t);
Thread y1 = new Thread(y);
t1.start();
y1.start();
}
}
class RunInstance implements Runnable{
TestInstance theinstance=new TestInstance();
public void run(){
theinstance.runtest();
}
}
(2)结果我们发现,两个线程用的都是m1这个方法,因为这时flag是个局部变量,它被创建了两次,
且并不会被线程互相访问,但是count 则不然,它是全局(严格说是static )变量,并且用了synchronized进行同步访问。
另外,请注意count = 2被打印两次,是因为Thread-0实行了 count++后,CPU等待Thread-1实行 count++
的结果。
Thread-0: m1's printing : count = 2
Thread-1: m1's printing : count = 2
Thread-0: m1's printing : count = 3
Thread-1: m1's printing : count = 4
Thread-0: m1's printing : count = 5
Thread-1: m1's printing : count = 6
Thread-0: m1's printing : count = 7
Thread-1: m1's printing : count = 8
Thread-0: m1's printing : count = 9
Thread-1: m1's printing : count = 10
Thread-0: m1's printing : count = 11
Thread-0: m1's printing : count = 13
Thread-1: m1's printing : count = 13
Thread-0: m1's printing : count = 14
Thread-1: m1's printing : count = 15
Thread-0: m1's printing : count = 16
Thread-1: m1's printing : count = 17
Thread-0: m1's printing : count = 18
Thread-1: m1's printing : count = 19
Thread-1: m1's printing : count = 20