Bootstrap

线程的创建方式

方式一:

继承java.lang.Thread类(线程子类)

public class SubThread extends Thread{
        public void run(){
            for(int i=0;i<100;i++){
                  System.out.println("子线程"+i+" ");
        }
    }
}
publci class MultiThread{
        public static void main(String[] args) {
              SubThread thd=new  SubThread();
                thd.start();
               for(int i=0;i<100;i++){
                    System.out.println(主线程""+i+" ");
                }
        }
}  

方式二:

实现java.lang.Runnable接口(线程执行类)

public class SubThread implements Thread{
        public void run(){
            for(int i=0;i<100;i++){
                  System.out.println("子线程"+i+" ");
        }
    }
}
publci class MultiThread{
        public static void main(String[] args) {
              SubThread t=new Thread(new  SubThread());
              t.start();
              for(int i=0;i<100;i++){
                    System.out.println(主线程""+i+" ");
                }
        }
}  

方式三:

实现java.util.concurrent.Callable接口,允许子线程返回结果,抛出异常

public class SubThread implements Callable<Integer>{
    private int begin,end;
    public SubThread (int begin,int end){
        this.begin=begin;
        this.end=end;
    }
    public Integer call() throws Exception{
            int result=0;
            for(int i=begin;i<end;i++){
                    result+=i;
            }
        return result;
    }
}
//为子线程封装成FutureTask对象
SubThread subThread1=new SubThread(1,100);
FutureTask<Intrger> task1=new FutureTask<>(subThread1);
//为子线程封装成FutureTask对象
SubThread subThread2=new SubThread(101,200);
FutureTask<Intrger> task2=new FutureTask<>(subThread2);
//分别启动两个子线程
new Thread(task1).start();
new Thread(task2).start();

//分别获取两个子线程的计算结构
int sum1=task1.get();
int sum2=task2.get();
//计算结果
int total=sum1+sum2;

方式四:

线程池

按照配置参数创建并管理若干线程对象。程序中如果需要线程,将一个执行任务传给线程池,线程池就会使用一个空闲的线程来执行这个任务。执行结束后,该线程不会死亡而是再次返回线程池成为空闲线程,等待下一个任务。

public class Demo01 {
	public static void main(String[] args) {
		//创建固定数目的线程池
		ExecutorService executorService=Executors.newFixedThreadPool(30);
		//提交10个打印字母线程的任务
		for(int i=1;i<=10;i++) {
			executorService.execute(()->{
				for(char c='A';c<'Z';c++) {
					System.out.println(Thread.currentThread().getName()+":"+c);
				}
			});
		}
		//提交了20个打印数字线程的任务
		for(int n=1;n<=20;n++) {
			executorService.execute(()->{
				for(int i=1;i<26;i++) {
					System.out.println(Thread.currentThread().getName()+":"+i);
					try {
						Thread.sleep(200);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			});
		}
		//关闭线程池
		executorService.shutdown();
	}
}

;