【发布时间】:2014-07-13 08:29:22
【问题描述】:
我正在尝试用两个线程打印数字 1-20:
- 偶数线程 - 仅打印偶数。
- 奇数线程 - 仅打印奇数。
我还有一个用于同步的锁对象。
我的应用程序卡住了。你能告诉我是什么问题吗?
我的代码:
public class runIt
{
public static void main(String[] args)
{
Odd odd = new Odd("odd thread");
Even even = new Even("even thread");
odd._t.start();
even._t.start();
try{
odd._t.join();
even._t.join();
}
catch (InterruptedException e){
System.out.println(e.getMessage());
}
}
}
public class Constants{
static Object lock = new Object();
}
public class Even implements Runnable{
Thread _t;
String _threadName;
public Even(String threadName){
_threadName = threadName;
_t = new Thread(this);
}
@Override
public void run(){
for (int i = 0; i < 20; i++){
if (i % 2 == 0){
synchronized (Constants.lock){
try{
Constants.lock.wait();
Constants.lock.notifyAll();
}
catch (InterruptedException e){
e.printStackTrace();
}
System.out.println(_threadName + " " + i + " ");
}
}
}
}
}
public class Odd implements Runnable{
Thread _t;
String _threadName;
public Odd(String threadName){
_threadName = threadName;
_t = new Thread(this);
}
@Override
public void run(){
for (int i = 0; i < 20; i++){
if (i % 2 == 1){
synchronized (Constants.lock){
try{
Constants.lock.wait();
Constants.lock.notifyAll();
}
catch (InterruptedException e1){
e1.printStackTrace();
}
System.out.println(_threadName + " " + i + " ");
}
}
}
}
}
我的输出应该是:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
感谢您的帮助, 谭。
【问题讨论】:
-
看看这里:stackoverflow.com/questions/6017281/… 这似乎正是你所需要的。
-
所以我想这意味着新学期刚刚开始? 叹息
-
您的直接问题是两个线程都进入了锁等待状态,然后它们永远不会收到通知。不过,此代码还存在一些其他问题。
-
@WarrenDew 说,“还有一些其他问题......”这是一个:你在构造函数中写了
new Thread(this)。在这段代码中,这可能不会对您造成任何问题,但是如果您想知道为什么它通常是一个坏主意,请使用谷歌“在构造函数中泄漏它”。
标签: java multithreading thread-safety deadlock thread-synchronization