【发布时间】:2015-11-06 05:51:57
【问题描述】:
在一次采访中,我被要求编写一个双线程 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? -
一种可能的改进是以无锁方式进行。
标签: java multithreading synchronization