User Tools

Site Tools


java-concurrent:thread

线程状态图

多线程方式

/**
 * 多线程实现的三种方式
 * 1 实现Runnable接口
 * 2 实现Callable接口
 * 3 继承Thread类
 * 实现接口会更好一些,因为:
 * Java 不支持多重继承,因此继承了 Thread 类就无法继承其它类,但是可以实现多个接口;
 * 类可能只要求可执行就行,继承整个 Thread 类开销过大。
 */
public class MainUsingThread {
 
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        MyRunnable myRunnable = new MyRunnable();
        Thread threadA = new Thread(myRunnable);
        threadA.start();
 
        MyCallable myCallable = new MyCallable();
        FutureTask<Integer> ft = new FutureTask<>(myCallable);
        Thread threadB = new Thread(ft);
        threadB.start();
        System.out.println(ft.get());
 
        MyThread myThread = new MyThread();
        myThread.start();
    }
}
 
 
public class MyCallable implements Callable<Integer> {
    @Override
    public Integer call() {
        System.out.println("run my callable");
        try {
            Thread.sleep(22000L);
        } catch (InterruptedException e) {
            System.out.println("I'm interrupted by others");
 
            e.printStackTrace();
        } finally {
        }
        return 123;
    }
}
 
public class MyRunnable  implements Runnable {
    public void run(){
        System.out.println("run my runnable");
 
        try {
            Thread.sleep(21000L);
        } catch (InterruptedException e) {
            System.out.println("I'm interrupted by others");
 
            e.printStackTrace();
        } finally {
        }
    }
}
 
public class MyThread extends Thread {
    public void run() {
        System.out.println("run my thread");
 
        try {
            Thread.sleep(20000L);
        } catch (InterruptedException e) {
            System.out.println("I'm interrupted by others");
 
            e.printStackTrace();
        } finally {
        }
    }
}

线程间通信

java-concurrent/thread.txt · Last modified: 2019/09/09 03:42 by 127.0.0.1

Except where otherwise noted, content on this wiki is licensed under the following license: 沪ICP备12046235号-2
Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki