| 多线程有两种实现方法,方式一:继承java.lang包下的Thread类,并重写Thread类的run()方法,在run()方法中实现运行在线程上的代码。 代码如下:
 复制代码public class Example {
        public static void main(String[] args) throws Exception{
                //创建线程MyThread的线程对象
                MyThread my=new MyThread ();
                my.start();//开启线程
                while(true){
                        System.out.println("main()方法在运行");
                }
                }
        }
class MyThread extends Thread{
        public void run (){
                while(true)//通过死循环打印输出
                {
                        System.out.println("MyThread类的run()方法在运行");
                }
                }
}
方式二:实现java.lang.Runnable接口,在run()方法中实现运行在线程上的代码。通过Thread(Runnable target)构造方法创建线程对象时,为其传递一个实现了Runnable接口的实例对象即可。
 代码如下:
 复制代码public class Example {
        public static void main(String[] args) throws Exception{
                //创建线程MyThread的实例对象
                MyThread my=new MyThread ();
                Thread th=new Thread(my);//创建线程对象
                th.start();//开启线程
                while(true){
                        System.out.println("main()方法在运行");
                }
        }
}
class MyThread implements Runnable{
        public void run(){
                while(true){
                        System.out.println("MyThread类的run()方法在运行");
                }
        }
}
 |