我们可以在Java中同步run()方法吗?
是的,我们可以run()
在Java中同步一个方法,但这不是必需的,因为该方法仅由单个线程执行。因此,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