java多线程学习笔记(一)——多线程的创建

来源:互联网 发布:人工智能投资机会 编辑:程序博客网 时间:2024/04/23 22:20

java多线程创建有三种方式:

  1. 继承Thread类
  2. 实现Runnable接口
  3. 实现Callable接口

代码示例:

1.继承Thread类代码实现

public class ThreadDemo1 extends Thread{    public static void main(String[] args)     {        //main线程先执行        System.out.println(Thread.currentThread().getName()+" is running.");        ThreadDemo1 th1=new ThreadDemo1();        //调用start方法才会启动线程        th1.start();        //main线程有可能会在子线程执行完之前结束        System.out.println(Thread.currentThread().getName()+" is end.");    }    //重新父类run方法    @Override    public void run()     {        //循环做延迟操作        for(int i=0;i<10;i++)         {            System.out.println(Thread.currentThread().getName()+" is running.i="+i);        }    }}

2.实现Runnable接口

public class ThreadDemo2 implements Runnable{    public static void main(String[] args)     {        System.out.println(Thread.currentThread().getName()+" is running.");        Thread th=new Thread(new ThreadDemo2());        th.start();        //实现匿名内部类实现        Thread th1=new Thread(new Runnable() {            @Override            public void run() {                // 循环做延迟操作                for (int i = 0; i < 10; i++)                 {                    System.out.println(Thread.currentThread().getName() + " is running.i=" + i);                }            }        });        th1.start();        //使用lambda表达式实现        Thread th2=new Thread(()-> {            // 循环做延迟操作            for (int i = 0; i < 10; i++)             {                System.out.println(Thread.currentThread().getName() + " is running.i=" + i);            }        });        th2.start();        System.out.println(Thread.currentThread().getName()+" is end.");    }    @Override    public void run() {        // 循环做延迟操作        for (int i = 0; i < 10; i++)         {            System.out.println(Thread.currentThread().getName() + " is running.i=" + i);        }    }}

3 实现Callable接口

public class ThreadDemo3 implements Callable<Integer>{    public static void main(String[] args) throws InterruptedException, ExecutionException {        System.out.println(Thread.currentThread().getName()+" is start");        ThreadDemo3 thCallable=new ThreadDemo3();        FutureTask<Integer> ft=new FutureTask<Integer>(thCallable);        Thread th=new Thread(ft);        th.start();        //调用FutureTask的get方法获取结果,主线程会阻塞到子线程结束,不调用get方法主线程会提前结束        System.out.println("计算从1到100之和为:"+ft.get());        System.out.println(Thread.currentThread().getName()+" is end");    }    //计算从1到100之和    @Override    public Integer call() throws Exception     {        int sum=0;        for(int i=1;i<=100;i++)         {            sum+=i;        }        System.out.println(Thread.currentThread().getName()+" count is done");        return sum;    }}

总结:

  1. java只支持单继承,实现接口的方式比继承Thread类常用。
  2. 匿名内部类、lambda表达式精简代码。
  3. Callable解决了没有返回值的问题。
阅读全文
0 0
原创粉丝点击