我正在尝试用两个线程打印数字 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
感谢您的帮助, 谭。
最佳答案
您可以在包声明中提到的站点中找到解释: 这是工作代码:
public class MultipleThreading {
int count = 1;
int MAX = 20;
public void printOdd() {
synchronized (this) {
while (count < MAX) {
while (count % 2 == 0) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(count + " ");
count++;
notify();
}
}
}
public void printEven() {
synchronized (this) {
while (count < MAX) {
while (count % 2 == 1) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(count + " ");
count++;
notify();
}
}
}
public static void main(String[] args) {
MultipleThreading mt = new MultipleThreading();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
mt.printEven();
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
mt.printOdd();
}
});
t1.start();
t2.start();
}
}
关于java - 在 Java 中用两个线程打印数字 1-20,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24720849/