写了多线程程序的顺序打印出单双号直到序列达到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; 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);
}
public void close()
{
System.exit(0);
}
}
你可以更具体一点吗? –
我刚刚用代码更新了我的答案。 – jedwards
试过了。当我去编译它时,它给了我一个'错误:找不到符号' –