创建多线程有几种方法?如何创建线程?

多线程有几种实现方法?

多线程实现又3种方法,其中前两中是常用的方法,推荐第二种方法,一个类应该在其修改或者加强是才继承

1.继承Thread类,重写run()方法,实例化该类,调用线程start()方法

(1)自定义类,继承Thread类,重写run()方法

(2)创建该Thread子类实例

(3)然后调用线程start()方法


    public class TestThread extends  Thread{
        @Override
        public void run() {
            printThreadMsg("1.2.new TestThread run");
        }
    }
    /**
     * 打印线程信息
     * @param msg
     */
    private void printThreadMsg(String msg)
    {
        System.out.println(msg+":threadName:"+Thread.currentThread().getName()+",threadId:"+Thread.currentThread().getId());
    }

        /**
         * 1.1 匿名内部类(继承Thread类,重写run()方法)
         */
        new Thread(){
            @Override
            public void run() {
                printThreadMsg("1.1 new Thread() run");
            }
        }.start();
        /**
         * 1.2 继承Thread类,重写run()方法
         */
        new TestThread().start();

2.实现Runnable接口,并实现该接口的run()的方法,

具体步骤:

(1)自定义类,并实现Runnable接口,实现run()方法

(2)创建Thread子类实例:用实现Runnable接口的对象作为参数实例化个Thread对象

(3)然后调用线程start()方法

    public class TestRunnable implements  Runnable{
        @Override
        public void run() {
            printThreadMsg("2.2.TestRunnable run");
        }
    }

   /**
         * 2.1实现Runnable接口,并实现该接口的run()的方法,然后用实现Runnable接口的对象作为参数实例化Thread对象
         */
        new Thread(new TestRunnable()).start();

        /**
         * 2.2实现Runnable接口,并实现该接口的run()的方法,然后用实现Runnable接口的对象作为参数实例化Thread对象
         */
        new Thread(new Runnable() {
            @Override
            public void run() {
                printThreadMsg("2.2. new Thread.new Runnable run");
            }
        }).start();



3.实现Callable接口,重写call()方法

(1)自定义类,实现Callable接口,实现call()方法

(2)实例化ExecutorService 对象,实例化个刚刚自定义类(实现Callable接口)的对象,把它作为参数调用submit()方法

(3)注意get()方法获取结果会造成阻塞

    public static  class   TestCallable implements Callable{
        @Override
        public Object call() throws Exception {
            /**
             * 沉睡6秒,模拟耗时操作
             */
            Thread.sleep(6000);
            System.out.println("3.TestCallable  call:threadName:"+Thread.currentThread().getName()+",threadId:"+Thread.currentThread().getId());

            return "这是 TestCallable call 执行完 返回的结果";
        }
    }

      /**
         *实现Callable接口,重写call()方法
         */
        ExecutorService mExecutorService= Executors.newSingleThreadExecutor();
        Future future=mExecutorService.submit(new TestCallable());
        try {
            /**
             * future.get()用来获取结果,  会造成线程阻塞,直到call()结束
             * 等待线程结束,并且返回结果
             * 线程阻塞了
             */
        String result= String.valueOf(future.get());
        System.out.println("3.TestCallable call return:"+result+","+Thread.currentThread().getName()+",threadId:"+Thread.currentThread().getId());

        } catch (Exception e) {
            e.printStackTrace();
        }

最后附上所有代码

package com.hex168.demo.therad;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import java.lang.ref.WeakReference;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * author:dz_hexiang on 2017/9/23 13:06
 * email:472482006@qq.com
 * 测试线程创建
 */
public class ThreadActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_therad);
        /**
         * 1.1 匿名内部类(继承Thread类,重写run()方法)
         */
        new Thread(){
            @Override
            public void run() {
                printThreadMsg("1.1 new Thread() run");
            }
        }.start();
        /**
         * 1.2 继承Thread类,重写run()方法
         */
        new TestThread().start();

        /**
         * 2.1实现Runnable接口,并实现该接口的run()的方法,然后用实现Runnable接口的对象作为参数实例化Thread对象
         */
        new Thread(new TestRunnable()).start();

        /**
         * 2.2实现Runnable接口,并实现该接口的run()的方法,然后用实现Runnable接口的对象作为参数实例化Thread对象
         */
        new Thread(new Runnable() {
            @Override
            public void run() {
                printThreadMsg("2.2. new Thread.new Runnable run");
            }
        }).start();


        /**
         *实现Callable接口,重写call()方法
         */
        ExecutorService mExecutorService= Executors.newSingleThreadExecutor();
        Future future=mExecutorService.submit(new TestCallable());
        try {
            /**
             * future.get()用来获取结果,  会造成线程阻塞,直到call()结束
             * 等待线程结束,并且返回结果
             * 线程阻塞了
             */
        String result= String.valueOf(future.get());
        System.out.println("3.TestCallable call return:"+result+","+Thread.currentThread().getName()+",threadId:"+Thread.currentThread().getId());

        } catch (Exception e) {
            e.printStackTrace();
        }
        /**
         * handler 及runnable都是在主线程
         */
        handler.post(handlerRunnable);
    }

    public class TestThread extends  Thread{
        @Override
        public void run() {
            printThreadMsg("1.2.new TestThread run");
        }
    }

    public class TestRunnable implements  Runnable{
        @Override
        public void run() {
            printThreadMsg("2.2.TestRunnable run");
        }
    }

    public Runnable handlerRunnable =new Runnable() {
        @Override
        public void run() {
            printThreadMsg("4.handler handlerRunnable run");
        }
    };

    /**
     * 打印线程信息
     * @param msg
     */
    private void printThreadMsg(String msg)
    {
        System.out.println(msg+":threadName:"+Thread.currentThread().getName()+",threadId:"+Thread.currentThread().getId());
    }

    private MyHandler handler=new MyHandler(this);
    static class MyHandler extends Handler{
        WeakReference<Activity> activityWeakReference;

        MyHandler(Activity c)
        {
            activityWeakReference=new WeakReference<Activity>(c);
        }
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    }

    public static  class   TestCallable implements Callable{
        @Override
        public Object call() throws Exception {
            /**
             * 沉睡6秒,模拟耗时操作
             */
            Thread.sleep(6000);
            System.out.println("3.TestCallable  call:threadName:"+Thread.currentThread().getName()+",threadId:"+Thread.currentThread().getId());

            return "这是 TestCallable call 执行完 返回的结果";
        }
    }
}

运行结果



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值