Tom*_*rud 1 java concurrency multithreading synchronized
我正在做一个关于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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
输出应该如下:
线程1被创建
线程2被创建
线程3被创建
线程4被创建
线程5被创建
变量
的当前值是1变量的当前值是2变量
的当前值是3变量
的当前值是4
,变量的当前值是5
但我得到的输出如下:
线程1创建
线程2创建
线程3创建
线程4创建
线程5创建
变量
的当前值为1变量的当前值为5变量
的当前值为4变量
的当前值3
是变量的当前值是2
每次当前值的顺序明显不同.
我得到的解决方案是不正确的?它显然无法实现其预期目的,即按顺序打印每个线程的值变量.
任何人都可以了解我是如何让它按照每次1到5的顺序打印线程数可靠吗?我认为使用synchronized 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.
Run Code Online (Sandbox Code Playgroud)
你永远不能保证Threads将以哪种顺序执行该方法,
因此,每次运行此程序时,您将获得一些不同的线程顺序
| 归档时间: |
|
| 查看次数: |
4044 次 |
| 最近记录: |