我正在做一个关于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 …Run Code Online (Sandbox Code Playgroud)