自学内容网 自学内容网

java中的Optional类和线程

Optional类:

public static <T> Optional<T> of(T value)

Returns an Optional describing the given non-null value.

通过非null值构建一个Optional容器,注意value不能为null,否则抛出异常

public static <T> Optional<T> ofNullable(T value)

Returns an Optional describing the given value, if non-null, otherwise returns an empty Optional

public T orElse(T other)

If a value is present, returns the value, otherwise returns the result produced by the supplying function.

如果返回值存在 ,返回返回值。

public boolean isPresent()

如果存在值,则返回true

 public T get()

如果Optianal中存在值,则返回值

线程创建

并发:在同一时刻,有多个任务在一个CPU下交替执行

并行:在同一时刻,有多个任务在多个CPU下同时执行

如何开发多线程:
方式一:Thread类

1:创建一个子类:继承Thread类

2:在子类中,重写让线程帮助完成的任务

//重写Thread类中的run方法

3:启动线程

//创建子类,继承Thread类
public class myThread extends Thread {
    @Override//重写run方法
    public void run()
    {
        System.out.println("新的线程已经启动");
        for(int i=0;i<20;i++)
        {
            System.out.println("线程:"+i);
        }
    }
}
public class threadDemo1 {
    public static void main(String[] args) {
        myThread thread1=new myThread();
        thread1.start();//底层自动调用run方法
    }

}

缺点:类只能单一继承 

线程任务,线程功能都在Thread的子类中

方式二: Runnable接口

1:创建一个子类,实现Runnable接口

2::在子类中,重写该接口的run方法

3:创建Thread类对象,并把实现了Runnable接口的子类对象,作为参数传给Thread类对象

4:启动线程(Thread类对象.start();)

public class myTask implements Runnable{

    @Override
    public void run() {
        for(int i=0;i<20;i++)
            System.out.println(i);
    }
}
public class threadDemo2 {
    public static void main(String[] args) {
        //创建任务线程对象
        myTask task=new myTask();

        //创建线程类对象
        Thread thread=new Thread(task);
        //启动线程
        thread.start();
    }
}

缺点:不能直接使用Thread类的方法

线程任务:Runnable接口实现类

线程功能:Thread类

好处:解耦

 Thread类的方法:

public final String getName()

Returns this thread's name.

public final void setName(String name)

Changes the name of this thread to be equal to the argument name.

public static Thread currentThread()

Returns the Thread object for the current thread.

获取当前正在运行的线程对象

public static void sleep(long millis) 

让当前线程休息(单位:毫秒)

 public final void join() throws InterruptedException

挂起其他线程 ,当前线程执行完后才会执行其他线程

class task implements Runnable
{

    @Override
    public void run() {
        Thread t=Thread.currentThread();//获取当前线程对象
        try {
            t.join();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        for(int i=0;i<200;i++)
        {
            System.out.println(t.getName()+":"+i);
        }
    }
}
public class test {
    public static void main(String[] args) throws InterruptedException {
        new Thread(new task()).start();
        Thread t1=Thread.currentThread();
        //t1.join();
        for(int i=0;i<500;i++)
        {
            System.out.println(i);
           Thread.sleep(1);
        }
    }
}


原文地址:https://blog.csdn.net/luosuss/article/details/137688897

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!