栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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 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();
        
    }
}

class MyCallable implements Callable{

    @Override
    public Integer call() throws Exception {
        for (int i = 0; i < 5; i++) {
            System.out.println("thread-name:" + Thread.currentThread().getName());
        }
        return 1024;
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/726491.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号