寫了多線程程序的順序打印出單雙號直到序列達到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
試過了。當我去編譯它時,它給了我一個'錯誤:找不到符號' –