能否在 Java 中将 run() 方法同步化?


是的,我们可以在 Java 中同步 run() 方法,但这不是必需的,因为此方法仅由一个线程执行。因此,run() 方法不需要同步。最好同步其他类的非静态方法,因为该方法会被多个线程同时调用。

示例

public class SynchronizeRunMethodTest implements Runnable {
   public synchronized void run() {
      System.out.println(Thread.currentThread().getName() + " is starting");
      for(int i=0; i < 5; i++) {
         try {
            Thread.sleep(1000);
            System.out.println(Thread.currentThread().getName() + " is running");
         } catch(InterruptedException ie) {
            ie.printStackTrace();
         }
      }
      System.out.println(Thread.currentThread().getName() + " is finished");
   }
   public static void main(String[] args) {
      SynchronizeRunMethodTest test = new SynchronizeRunMethodTest();
      Thread t1 = new Thread(test);
      Thread t2 = new Thread(test);
      t1.start();
      t2.start();
   }
}

输出

Thread-0 is starting
Thread-0 is running
Thread-0 is running
Thread-0 is running
Thread-0 is running
Thread-0 is running
Thread-0 is finished
Thread-1 is starting
Thread-1 is running
Thread-1 is running
Thread-1 is running
Thread-1 is running
Thread-1 is running
Thread-1 is finished

更新日期:28-Nov-2023

3K+ 浏览

开启你的职业生涯

通过完成课程获得认证

开始
广告