Java 并发编程之创建多线程方法

进程是处于运行过程中的程序;线程是进程中的一个执行单元;一个程序运行后至少有一个进程,一个进程中可以包含多个线程。

1)继承 Thread 类

public class MyThread extends Thread{
    @Override
    public void run() {
        for (int i=0; i<5; i++) {
            try {
                TimeUnit.SECONDS.sleep(1);
                System.out.println("MyThread");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

2)实现 Runnable 接口

public class MyRunnable implements Runnable{
    @Override
    public void run() {
        for (int i=0; i<5; i++) {
            try {
                TimeUnit.SECONDS.sleep(1);
                Thread.yield();
                System.out.println("MyRunnable");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

3)实现 Callable 接口

public class MyCallable implements Callable<String> {
    @Override
    public String call() throws Exception {
        TimeUnit.SECONDS.sleep(15);
        System.out.println("MyCallable");
        return "completed";
    }
}

多线程的使用:

public class CreateThread {
    public static void main(String[] args) {
        new MyThread().start();
        new Thread(new MyRunnable()).start();
        Thread c = new Thread(new FutureTask<String>(new MyCallable()));
        c.start();
        try {
            c.join();
            System.out.println("CreateThread");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

猜你喜欢

转载自blog.csdn.net/suoyx/article/details/115420285