Java多线程实现方式

多线程实现方式

  • 四种:继承Thread类实现Runnable接口匿名内部类实现Callable接口

  • 用Runnable与Callable接口的方式创建多线程的特点:

    1. 线程类只是实现了Runnable接口或Callable接口,还可以继承其它类。

    2. 在这种方式下,多个线程可以共享一个target对象,所以非常适合多个线程来处理同一份资源情况。

    3. 如果需要访问当前线程,需要使用Thread.currentThread方法。

    4. Callable接口与Runnable接口相比,只是Callable接口可以返回值而已。

  • 用Thread类的方式创建多线程的特点:

    1. 因为线程已经继承Thread类,所以不可以再继承其它类。

    2. 如果需要访问当前线程,直接使用this即可。

1.继承Thread类

//继承Thread类
public class test1 extends Thread{
    @Override
    public void run() {
        String str = "hello";
        char[] chars = str.toCharArray();
        try {
            for (int i=0;i<str.length();i++){
                System.out.print(chars[i]);
                Thread.sleep(1000);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        test1 t = new test1();
        t.start();
    }
}

2.实现Runnable接口

//Runnable接口实现
public class test2 {
    public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String st = "hello";
                char[] c = st.toCharArray();
                try {
                    for (int i=0;i<c.length;i++){
                        System.out.println(c[i]);
                        Thread.sleep(1000);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }
}

3.匿名内部类

//匿名内部类实现
public class tset2 {
    public static void main(String[] args) {
        tset2.MyThread t = new tset2().new MyThread();
        t.start();
    }
    class MyThread extends Thread{
        @Override
        public void run() {
            String str = "hello";
            char[] chars = str.toCharArray();
            try {
                for (int i=0;i<str.length();i++){
                    System.out.print(chars[i]);
                    Thread.sleep(1000);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

4.实现Callable接口

//Callable实现多线程
public class test4 implements Callable<String> {
    @Override
    public String call() {
        String st = "hello";
        char[] c = st.toCharArray();
        try {
            for (int i=0;i<c.length;i++){
                System.out.print(c[i]);
                Thread.sleep(1000);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return st;
    }
    public static void main(String[] args) {
        test4 rt = new test4();
        // 使用FutureTask来包装Callable对象
        FutureTask<String> task = new FutureTask<>(rt);
        new Thread(task).start();
    }
}

猜你喜欢

转载自blog.csdn.net/hk10066/article/details/83421490