写了一个多线程程序,依次打印出奇偶数,直到序列达到30。
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
public class NumPrintTX
{
public static void main(String[] args)
{
final int max = 31;
final AtomicInteger i = new AtomicInteger(0);
Executor dd = Executors.newFixedThreadPool(2);
final Object lock = new Object();
dd.execute(new Runnable()
{
@Override
public void run()
{
while (i.get() < max)
{
if (i.get() % 2 == 0)
{
System.out.print(" " + i.getAndAdd(1));
synchronized(lock)
{
lock.notify();
}
}
else
{
synchronized(lock)
{
try
{
lock.wait();
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
});
dd.execute(new Runnable()
{
@Override
public void run()
{
while (i.get() < max)
{
if (i.get() % 2 != 0)
{
System.out.print(" " + i.getAndAdd(1));
synchronized(lock)
{
lock.notify();
}
}
else
{
synchronized(lock)
{
try
{
lock.wait();
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
});
do
{
try
{
Thread.currentThread().sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
while (i.get() != max);
}
}
当程序运行时,结果很好,但它不会转到下一行,所以我可以输入另一个命令来执行我接下来想做的任何事情。任何想法为什么会这样以及我能做些什么来解决它?
修改代码:import java.util.concurrent.Executor;导入 java.util.concurrent.Executors;导入 java.util.concurrent.atomic.AtomicInteger;
public class NumPrintTX
{
public static void main(String[] args)
{
final int max = 31;
final AtomicInteger i = new AtomicInteger(0);
Executor dd = Executors.newFixedThreadPool(2);
final Object lock = new Object();
dd.execute(new Runnable()
{
@Override
public void run()
{
while (i.get() < max)
{
if (i.get() % 2 == 0)
{
System.out.print(" " + i.getAndAdd(1));
synchronized(lock)
{
lock.notify();
}
}
else
{
synchronized(lock)
{
try
{
lock.wait();
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
});
dd.execute(new Runnable()
{
@Override
public void run()
{
while (i.get() < max)
{
if (i.get() % 2 != 0)
{
System.out.print(" " + i.getAndAdd(1));
synchronized(lock)
{
lock.notify();
}
}
else
{
synchronized(lock)
{
try
{
lock.wait();
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
});
do
{
try
{
Thread.currentThread().sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
while (i.get() != max);
}
public void close()
{
System.exit(0);
}
}