在多线程中我们可以使用 匿名类,是程序高效运行。
如下代码,在main函数中 有三段不相关的代码块,若x很大的情况下,其余两段代码块 就很难 被执行。
class ThreadTest
{
public static void main(String[] args)
{
for (int x=0;x<100;x++)
{
System.out.println(Thread.currentThread().getName()+"....." +x);
}
for (int x=0;x<100;x++)
{
System.out.println(Thread.currentThread().getName()+"....." +x);
}
for (int x=0;x<100;x++)
{
System.out.println(Thread.currentThread().getName()+"....." +x);
}
}
}
因此,我们可以采用多线程的方式来改写程序,同时为了简化代码,我们可以使用匿名内部类的方式,定义多线程代码块,来提高程序的运行效率,如下所示:
class ThreadTest
{
public static void main(String[] args)
{
new Thread()
{
public void run()
{
for (int x=0;x<20;x++)
{
System.out.println(Thread.currentThread().getName()+"....." +x);
}
}
}.start();
for (int x=0;x<20;x++)
{
System.out.println(Thread.currentThread().getName()+"....." +x);
}
Runnable r= new Runnable()
{
public void run()
{
for (int x=0;x<20;x++)
{
System.out.println(Thread.currentThread().getName()+"....." +x);
}
}
};
new Thread(r).start();
}
}