我们可以在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 好听的元旦简短祝福语