Java多线程学习 Runnable接口

Java多线程学习 Runnable接口

不多说 看源码

@FunctionalInterface
public interface Runnable {
    public abstract void run();
}

​ 首先可以看到函数式接口 可以使用lambda表达式

​ 其次抽象的run方法 说明必须得 复写

​ 没有start方法 那么怎么 启动呢?

​ 看看Thread类里的构造方法

 ```txt

Thread​(Runnable target)
Allocates a new Thread object.

Thread​(Runnable target, String name)
Allocates a new Thread object.
```

上代码

class Mythread implements Runnable {
    private String title;
    public Mythread (String title) {
        this.title = title;
    }
    @Override
    public void run() {
        for (int i = 0 ; i < 10; i++) {
            System.out.println(this.title+"线程:"+i);
        }
    }
}
public class duoxianc {
    public static void main(String args[]) {
        Thread my = new Thread(new Mythread("线程A"));
        Thread mya = new Thread(new Mythread("线程B"));
        Thread myb = new Thread(new Mythread("线程C"));
        my.start();
        mya.start();
        myb.start();
    }
}

注意 是 Thread

Mythread继承了Runnble接口 根据 Thred类里得 构造方法 可以定义这样的形式

这样 才是一个 标准化的 接口实现吧

使用lamdba表达式


class Mythread implements Runnable {
    private String title;
    public Mythread (String title) {
        this.title = title;
    }
    @Override
    public void run() {
        for (int i = 0 ; i < 10; i++) {
            System.out.println(this.title+"线程:"+i);
        }
    }
}
public class duoxianc {
    public static void main(String args[]) {
       for (int x = 0 ; x < 3 ;x++) {
           String title = "线程对象 - " + x;
           new Thread(()->{
               for (int y = 0 ; y < 10 ; y++) {
                   System.out.println(title + "运行 x = " + y);
               }
           }).start();
       }
    }
}


原文地址:https://www.cnblogs.com/laowt/p/14508528.html