3种启动线程的方式

线程和进程的关系:  一个进程有N个线程

 

1、实现线程的三种方式:

(1)继承thread 类

    [1]创建一个继承thread类的类

    

package Thread01;

public class MyThread extends Thread {
    private int i;

    @Override
    public void run() {
       for (; i < 10; i++) {
         System.out.println(getName()+"\t"+i);
    }
    }
}

 

    [2]创建测试类

package Thread01;

public class MyTest {
    public static void main(String[] args) {
        for (int i = 0; i <10; i++) {
             System.out.println(Thread.currentThread().getName()+"\t"+i+"======");
             if(i==5){
                 
                 MyThread mt2 =new MyThread();
                 MyThread mt =new MyThread();
                 mt2.start();
                 mt.start();
             }
        }
    }
    
    public static long getMemory() {
           return Runtime.getRuntime().freeMemory();
        }
}

 

(2)实现runnable 接口

 

  【1】 实现runnable 接口的类并不是一个线程类,而是线程类的一个target ,可以为线程类构造方法提供参数来实现线程的开启

     

package Thread02;

public class SecondThread implements Runnable{
    private int i;
    public void run() {
        for (; i < 20; i++) {
            System.out.println(Thread.currentThread().getName()+" "+i);
            if(i==20)
            {
                System.out.println(Thread.currentThread().getName()+"执行完毕");
            }
        }
    }
}

 

  【2】测试类

package Thread02;

public class MyTest {
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName()+" "+i);
            if(i==5)
            {
                SecondThread s1=new SecondThread();
                Thread t1=new Thread(s1,"线程1");
                Thread t2=new Thread(s1,"线程2");
                t1.start();
                t2.start();
               
            }
        }
    }
}

 

(3)实现callable 接口

  【1】创建callable 实现类

  

package Thread03;

import java.util.concurrent.Callable;

public class Target implements Callable<Integer> {
    int i=0;
    public Integer call() throws Exception {
        for (; i < 20; i++) {
            System.out.println(Thread.currentThread().getName()+""+i);
        }
        return i;
    }

}

 

  【2】测试类

  

package Thread03;

import java.util.concurrent.FutureTask;

public class ThirdThread {
     public static void main(String[] args) {
            Target t1=new Target();
            FutureTask<Integer> ft=new FutureTask<Integer>(t1);
            Thread t2=new Thread(ft,"新线程");
            t2.start();
            try {
                System.out.println(ft.get());
            } catch (Exception e) {
                // TODO: handle exception
            }
    }
}

 

posted on 2017-01-07 18:52 卅年 阅读(...) 评论(...) 编辑 收藏

导航

公告