在一个程序中,如果有一个或多个耗时很长的计算,在单线程程序中,每个计算要依次完成,一个计算要在完全结束后,其他计算才能进行,如下程序:
class dog
{
public void run()
{
while(true)
{
System.out.println("a dog is running!");
}
}
}
class cat
{
public void run()
{
while(true)
{
System.out.println("a cat is running!");
}
}
}
class mouse
{
public void run()
{
while(true)
{
System.out.println("a mouse is running!");
}
}
}
class myThread
{
public static void main(String[] aaa)
{
dog d=new dog();
d.run();
cat c=new cat();
c.run();
mouse m=new mouse();
m.run();
}
}
结果:
a dog is running!
a dog is running!
a dog is running!....
程序运行时,dog类的run方法一直在运行,其他类的方法得不到运行的机会。
使用Thread类实现多线程:
class dog extends Thread
{
public void run()
{
while(true)
{
System.out.println("a dog is running!");
}
}
}
class cat extends Thread
{
public void run()
{
while(true)
{
System.out.println("a cat is running!");
}
}
}
class mouse extends Thread
{
public void run()
{
while(true)
{
System.out.println("a mouse is running!");
}
}
}
class myThread
{
public static void main(String[] aaa)
{
Thread t1=new dog();
t1.start();
Thread t2=new cat();
t2.start();
Thread t3=new mouse();
t3.start();
}
}
Dog类方法、cat类和mouse类的方法都能得到执行
但是要注意两点:
1,多线程的类的函数令名必须是run。
2,主类不能写成这个样子:
class myThread
{
public static void main(String[] aaa)
{
dog d=new dog();
d.run();
cat c=new cat();
c.run();
mouse m=new mouse();
m.run();
}
}
其他办法:
//使用Runnable接口实现多线程:
class dog implements Runnable
{
public void run()
{
while(true)
{
System.out.println("a dog is running!");
}
}
}
class cat implements Runnable
{
public void run()
{
while(true)
{
System.out.println("a cat is running!");
}
}
}
class mouse implements Runnable
{
public void run()
{
while(true)
{
System.out.println("a mouse is running!");
}
}
}
class myThread
{
public static void main(String[] aaa)
{
Thread t1=new Thread(new dog());
t1.start();
Thread t2=new Thread(new cat());
t2.start();
Thread t3=new Thread(new mouse());
t3.start();
}
}
//使用内部类实现多线程
class ST
{
public void run()
{
Thread t1=new Thread(new dog());
t1.start();
Thread t2=new Thread(new cat());
t2.start();
Thread t3=new Thread(new mouse());
t3.start();
}
class dog implements Runnable
{
public void run()
{
while(true)
{
System.out.println("a dog is running!");
}
}
}
class cat implements Runnable
{
public void run()
{
while(true)
{
System.out.println("a cat is running!");
}
}
}
class mouse implements Runnable
{
public void run()
{
while(true)
{
System.out.println("a mouse is running!");
}
}
}
}
class myThread
{
public static void main(String[] aaa)
{
ST t=new ST();
t.run();
}
}
*线程同步问题
*synchronized方法
两种多线程方法的比较:
Thread是JAVA已经严格封装好的类,因为有认为错误,对一个类继承,修改或者扩充,将可能导致该子类出现不可预测的错误。同时JAVA不支持多重继承。这个是继承Thread的缺点。但有时候要获得用于特殊功能的线程必须通过继承并扩充Thread实现。若对其修改或扩充不大,可以权衡使用。
使用Runnable的缺点就是调用自己的线程需要调用Thread.currentThread()。比继承Thread麻烦点。