我们可以在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
热门推荐
10 香港老妈结婚祝福语简短
11 毕业立体贺卡祝福语简短
12 简短新年年会祝福语
13 评论小品祝福语大全简短
14 恭喜师兄结婚祝福语简短
15 员工集体辞职祝福语简短
16 高中新生祝福语 简短
17 装修祝福语男生搞笑简短
18 生日开业蛋糕祝福语简短