java中对线程理解以及创建方式

java中对线程理解以及创建方式

1,进程和线程的对比

进程:是一个程序的集合
线程:一个进程中包含多个线程

2,线程的几种状态

NEW:新建
RUNNABLE:运行中
BLOCKED:线程阻塞
WAITING:线程等待
TIMED_WAITING:线程超时等待
TERMINATED:线程终止

在这里插入图片描述

3,创建线程的三种方式

方式一:继承Thread类

public class ThreadDemo extends Thread{


    public ThreadDemo(){}

    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println("thread-name:" + Thread.currentThread().getName());
        }
    }

    public static void main(String[] args) {
        ThreadDemo thread01 = new ThreadDemo();
        ThreadDemo thread02 = new ThreadDemo();
        ThreadDemo thread03 = new ThreadDemo();
        thread01.start();
        thread02.start();
        thread03.start();
    }
}

方式二:实现Runnable接口

public class ThreadRunnableDemo implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println("thread-name:" + Thread.currentThread().getName());
        }
    }
}
class TestRunnable{
    public static void main(String[] args) {
        ThreadRunnableDemo threadRunnable = new ThreadRunnableDemo();
        Thread thread01 = new Thread(threadRunnable, "线程1");
        Thread thread02 = new Thread(threadRunnable, "线程2");
        Thread thread03 = new Thread(threadRunnable, "线程3");
        thread01.start();
        thread02.start();
        thread03.start();
    }
}

方式三:实现Callable接口

public class CallableTest {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        MyCallable myCallable = new MyCallable();
        FutureTask<Integer> futureTask = new FutureTask<>(myCallable);
        new Thread(futureTask).start();
        Thread thread1 = new Thread(futureTask,"thread-01");
        Thread thread2 = new Thread(futureTask,"thread-02");
        Thread thread3 = new Thread(futureTask,"thread-03");
        thread1.start();
        thread2.start();
        thread3.start();
        /*Integer integer = futureTask.get();
        System.out.println(integer);*/
    }
}

class MyCallable implements Callable<Integer>{

    @Override
    public Integer call() throws Exception {
        for (int i = 0; i < 5; i++) {
            System.out.println("thread-name:" + Thread.currentThread().getName());
        }
        return 1024;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值