小编Tom*_*rud的帖子

静态变量的Java同步方法

我正在做一个关于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)

java concurrency multithreading synchronized

1
推荐指数
1
解决办法
4044
查看次数

标签 统计

concurrency ×1

java ×1

multithreading ×1

synchronized ×1