多线程是指同时执行多段代码,多线程有两种方式实现,下面用一段程序来演示多线程技术.
/*
class test implements Runnable //多线程的步骤1,实现Runnable借口
{
//多线程的步骤2,实现Runnable借口
public void run()
{
for(int i=0; i<100; i++)
{
System.out.println("func...2");
}
}
}
class RunnableDemo
{
public static void main(String[] args)
{
test t = new test();
//创建Thread对象,调用start函数启动新线程
new Thread(t).start();
for(int i=0; i<100; i++)
{
System.out.println("main...1");
}
}
}
/********************第二种方式********************/
class PrimeThread extends Thread //继承Thread类
{
PrimeThread(String name)
{
super(name);
}
public void run()
{
for (int i = 0; i < 60; i++)
{ //获取当前线程对象的引用 获取线程名字
System.out.println((Thread.currentThread().getName())+"--run----"+getName());
}
}
}
class ThreadDemo
{
public static void main(String[] args)
{
PrimeThread t = new PrimeThread("Pack");
t.start(); //启动多线程,并且执行run()
for (int i = 0; i < 60; i++)
{
System.out.println("Main----"+i);
}
}
}
两种方法建议使用实现Runnable接口的方法,若使用第二种方法的话,此类就不可以再继承其他的类了。
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
提醒:
使用多线程是有代价的,如果程序是计算密集型且每一步都有依赖,那么使用线程反而会导致效率下降,因为多个线程之间需要切换,还要负责加锁等。对于可并行的计算密集型问题和I/O与计算可重叠的问题使用多线程一般会达到显著的效果。程序中有多个可并发的模块的时候,使用线程也能提高程序的响应速度。