我被要求在一次採訪中編寫一個雙線程Java程序。在這個程序中,一個線程應該打印偶數,另一個線程應該打印奇數。多線程java程序打印偶數和奇數
示例輸出:
線程1:1
線程2:2
線程1:3
線程2:4 ...等等
我寫了下面程序。一類Task
其中包含兩種分別打印偶數和奇數的方法。從main方法中,我創建了兩個線程來調用這兩個方法。面試官讓我進一步改進,但我想不出有什麼改進。有沒有更好的方法來編寫同一個程序?
class Task
{
boolean flag;
public Task(boolean flag)
{
this.flag = flag;
}
public void printEven()
{
for(int i = 2; i <= 10; i+=2)
{
synchronized (this)
{
try
{
while(!flag)
wait();
System.out.println(i);
flag = false;
notify();
}
catch (InterruptedException ex)
{
ex.printStackTrace();
}
}
}
}
public void printOdd()
{
for(int i = 1; i < 10; i+=2)
{
synchronized (this)
{
try
{
while(flag)
wait();
System.out.println(i);
flag = true;
notify();
}
catch(InterruptedException ex)
{
ex.printStackTrace();
}
}
}
}
}
public class App {
public static void main(String [] args)
{
Task t = new Task(false);
Thread t1 = new Thread(new Runnable() {
public void run()
{
t.printOdd();
}
});
Thread t2 = new Thread(new Runnable() {
public void run()
{
t.printEven();
}
});
t1.start();
t2.start();
}
}
不確定。但也許面試官正在尋找使用'CyclicBarrier'? – TheLostMind
可能的改進是以無鎖方式進行。 – mattinbits