java基础之Thread

2017-05-13  本文已影响6人  watayouxiang

线程

创建线程的方式

继承Thread类

public class Demo {
    public static void main(String[] args) {
        MyThread mt = new MyThread(); //4, 创建自定义类的对象
        mt.start(); //5, 开启线程
    }
}

class MyThread extends Thread { //1, 定义类继承Thread
    public void run() { //2, 重写run方法
        for(int i = 0; i < 3000; i++) { //3, 将要执行的代码, 写在run方法中
            System.out.println("hello");
        }
    }
}

实现Runnable接口

public class Demo2 {
    public static void main(String[] args) {
        MyRunnable mr = new MyRunnable(); //4, 创建自定义类对象
        Thread t = new Thread(mr); //5, 将 "自定义类对象" 当作参数传递给Thread的构造函数
        t.start(); //6, 开启线程
    }
}

class MyRunnable implements Runnable { //1, 自定义类实现Runnable接口
    @Override
    public void run() { //2, 重写run方法
        for(int i = 0; i < 3000; i++) { //3, 将要执行的代码写在run方法中
            System.out.println("hello");
        }
    }
}

匿名内部类实现两种线程的创建

// 继承Thread类
new Thread() { 
    public void run() {
        for(int i = 0; i < 3000; i++) {
            System.out.println("hello");
        }
    }
}.start();

// 实现Runnable接口
new Thread(new Runnable(){
    public void run() {
        for(int i = 0; i < 3000; i++) {
            System.out.println("hello");
        }
    }
}).start(); 
上一篇下一篇

猜你喜欢

热点阅读