java多线程

1、继承Thread类实现多线程

package org.hanqi.zwxx;

//1、新建类TestThread,继承Thread类
public class TestThread  extends Thread {
    
//2、覆盖run()方法    
    public void run()
    {
        for(int i=0;i<10;i++)
        {
            System.out.print(i+" ");
            
            try {
                Thread.sleep(1000);//每隔1秒输出
            } catch (InterruptedException e) {
                // TODO 自动生成的 catch 块
                e.printStackTrace();
            }
        }

    }
 public static void main(String[] args) {
 
  //3、main方法中实例化            
        TestThread tt1=new TestThread();
        
  //4、调用父类的start()方法启动多线程
        tt1.start();
        
        TestThread tt2=new TestThread();
        
        tt2.start();
    }

}
View Code

 

2、采用Runnable接口实现多线程

package org.hanqi.zwxx;

//1、新建类TestThread,添加Runnable接口
public class TestThread  implements Runnable {

//2、实现run()方法,由run()方法调用需要多线程的代码
    @Override
    public void run() {
        // TODO 自动生成的方法存根
        
        for(int i=0;i<10;i++)
        {
            System.out.print(i+" ");
            
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO 自动生成的 catch 块
                e.printStackTrace();
            }
        }
    }
    
    public static void main(String[] args) {
        
//3、新建一个Runnable的实现类
        TestThread t=new TestThread();
        
//4、调用Thread的构造方法,传一个Runnable的实现类
        Thread t1=new Thread(t);
        
//5.调用start()    
        t1.start();
        
        Thread t2=new Thread(t);
        
        t2.start();
        
        Thread t3=new Thread(t);
        
        t3.start();    
    }

}
View Code

 

posted @ 2016-03-15 16:30  1011042043  阅读(167)  评论(0编辑  收藏  举报