[英]Java Synchronized Method on Static Variable
我正在上一门关于Java并发的大学课程,最近得到了一个简单的任务,创建5个线程,编号从1到5,然后让每个线程使用同步的静态方法将其线程号写入类中的静态变量。
讲师给我的解决方案如下:
public class thread1 extends Thread {
private int threadNumber;
private static int threadCount = 0;
private static int value;
public thread1(){
threadNumber = ++threadCount;
System.out.println("Thread " + threadNumber + " is created" );
}
public synchronized static void setValue(int v){
value = v;
try{
Thread.currentThread().sleep(100);
}
catch(InterruptedException e ){}
System.out.println("the current value of the variable is " + value);
}
public void run() {
setValue(threadNumber);
return;
}
public static void main(String[] args) {
for(int i = 0; i < 5; i++){
thread1 thr = new thread1();
thr.start();
}
}
}
输出应如下所示:
创建线程1
创建线程2
创建线程3
创建线程4
创建线程5
变量的当前值为1
变量的当前值为2
变量的当前值为3
变量的当前值为4
变量的当前值为5
但是我得到的输出如下:
创建线程1
创建线程2
创建线程3
创建线程4
创建线程5
变量的当前值为1
变量的当前值为5
变量的当前值为4
变量的当前值为3
变量的当前值为2
当前值的顺序每次都明显不同。
我得到的解决方案不正确吗? 很显然,它无法实现其预期的目的,即按顺序打印出每个线程的值变量。
有人能阐明我如何可靠地每次以1到5的顺序打印线程号吗? 我认为使用同步的setValue方法可以解决问题,但显然不能。
您的讲师提供的解决方案绝对正确。
您没有得到预期的顺序,因为创建了5个不同的线程,并且每个线程都必须访问相同的同步方法。
当方法同步时,一次只能访问一个对象
在您的情况下,只有一个线程可以访问setValue方法 ,
when one Thread enters the method it acquires the lock and
the other threads wait for the lock ,when this Thread releases the lock ,
any waiting Thread can acquire it and execute the setValue method.
您永远无法保证Threads将以哪种顺序执行方法 ,
因此,每次运行该程序时,您将获得一些不同顺序的线程
无法保证线程将按照您对它们调用start方法的顺序执行。 同步块仅意味着两个线程不能同时访问它。 线程的运行顺序由调度程序确定。
没有定义线程进入监视器的顺序。 一旦线程在监视器内完成执行,则在该监视器上等待的任何其他线程都可以控制关键部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.