一.用继承方法实现多线程
public class MultiThread {
public static void main(String[] args)
{
Th t=new Th();
//t.setDaemon(true); //定义为后台执行线程,当主线程结束,后台线程也结束;
t.setPriority(Thread.MAX_PRIORITY);//也有MIN_PRIORITY,NONE_PRIORITY;
t.start(); //线程开始执行
int index=0;
while (true )
{
if(index++==1000) //index的值增加,index++的值也增加
break;
System.out.println("main:"+Thread.currentThread().getName());
}
}
}
class Th extends Thread{
public void run()
{
while(true)
{
System.out.println(getName()+"thread2");
yield(); //放弃其执行的权利,让别的进程优先执行
}
}
}
注意:(1)定义优先级,java虚拟机并不是先只执行优先级高的程序,而不执行优先级低的程序,长时间被放置的优先级比较低的程序也可被执行;
(2)计算机在同一时刻只执行一个线程,但多线程交替执行;
二.用接口实现多线程实例:
public class MultiThread2 {
public static void main(String[] args)
{
Thread2 t=new Thread2();
new Thread(t).start();
System.out.println(Thread.currentThread().getName());
}
}
class Thread2 implements Runnable
{
public void run()
{
System.out.println(Thread.currentThread().getName());
}
}
优点:(1)用接口可以创建一个可以继承其他类的线程;
(2)可以使主类中创建的进程拥有同一个变量;