【发布时间】:2012-05-26 14:55:27
【问题描述】:
正如我们所知,没有任何规定可以防止多个线程使用start() 方法调用run() 方法。我确实创建了两个对象m1 和m2 都调用同一个线程来运行。
我需要确保第一个对象完成 (m1.start) 的执行,方法是在第二个对象执行开始之前调用线程。
我的问题是为什么我不能在我创建的线程(即MyThread1)中使用synchronized 关键字和run() 方法?
我尝试在我创建的线程中使用“同步”来运行()方法,但它给出了任意输出(换句话说,m2 不会等待m1 完成执行)。
您可以在程序的最底部看到我得到的输出。
public class ExtendedThreadDemo {
public static void main(String[] args) {
Mythread1 m1 =new Mythread1();
Mythread1 m2 =new Mythread1();
m1.start();
m2.start();
System.out.println(" main thread exiting ....");
}
}
我的线程
public class MyThread1 extends Thread {
public synchronized void run() {
for(int i=1; i<5; i++) {
System.out.println(" inside the mythread-1 i = "+ i);
System.out.println(" finish ");
if (i%2 == 0) {
try {
Thread.sleep(1000);
} catch(InterruptedException e) {
System.out.println(" the thread has been interrupted ");
}
}
}
}
}
输出
main thread exiting ....
inside the mythread-1 i = 1
finish
inside the mythread-1 i = 2
finish
inside the mythread-1 i = 1
finish
inside the mythread-1 i = 2
finish
inside the mythread-1 i = 3
finish
inside the mythread-1 i = 4
finish
inside the mythread-1 i = 3
finish
inside the mythread-1 i = 4
finish
正如您在i = 2 之后看到的,第二个对象(即m2.start())开始执行。
【问题讨论】:
-
如果你想让它同步,你为什么需要它在扩展线程的类中?只需将其移动到单独的一个。
-
同步运行方法有零点。什么,你想启动 5 个线程,让它们可以互相等待完成?这与让一个线程连续执行五次
run完全相同,只是开销更大。
标签: java multithreading synchronized