Thread类和Runnable接口实现多线程--2019-4-18

Posted fzly-88

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Thread类和Runnable接口实现多线程--2019-4-18相关的知识,希望对你有一定的参考价值。

1.通过Thread实现

public class TestThread extends Thread{ 
    public TestThread(String name) {
        super(name);
    } 

    public void run() {
        for(int i = 0;i<5;i++){
            for(long k= 0; k <100000000;k++);
            System.out.println(this.getName()+" :"+i);
        } 
    } 

    public static void main(String[] args) {
        Thread t1 = new TestThread("阿三");
        Thread t2 = new TestThread("李四");
        t1.start(); 
        t2.start(); 
    } 
}

2.Runnable接口实现

public class DoSomething implements Runnable {
    private String name;

    public DoSomething(String name) {
        this.name = name;
    } 

    public void run() {
        for (int i = 0; i < 15; i++) {
            for (long k = 0; k < 100000000; k++) ;
            System.out.println(name + ": " + i);
        } 
    } 
}
public class TestRunnable {
    public static void main(String[] args) {
        DoSomething ds1 = new DoSomething("阿三");
        DoSomething ds2 = new DoSomething("李四");

        Thread t1 = new Thread(ds1);
        Thread t2 = new Thread(ds2);

        t1.start(); 
        t2.start(); 
    } 
}

 

以上是关于Thread类和Runnable接口实现多线程--2019-4-18的主要内容,如果未能解决你的问题,请参考以下文章

Thread类和Runnable接口实现多线程--2019-4-18

多线程学习记录一继承Thread类和实现Runnable接口Callable接口的区别

Java多线程学习笔记— “建立线程的两种方法 (Thread类和Runnable接口)”

Java多线程和并发,Thread类和Runnable接口

多线程:Thread类和Runnable接口

Java 多线程