java多线程(一)——简单多线程demo

时间:2021-06-02 12:39:26   收藏:0   阅读:0

创建线程

1.继承Thread类,重写run()方法

public class ThreadCreateDemo1 {
    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start(); //该方法调用多次,出现IllegalThreadStateException
    }
}

class MyThread extends Thread {
    @Override
    public void run() {
        super.run();
        System.out.println("hellow_world!");
    }
}

 

2.实现Runable接口,传参给Thread构造方法

public class ThreadCreateDemo2 {
    public static void main(String[] args) {
        Runnable runnable = new MyRunnable();
        Thread thread = new Thread(runnable);
        thread.start();
    }
}

class MyRunnable implements Runnable {
    public void run() {
        System.out.println("通过Runnable创建的线程!");
    }
}

线程运行结果与执行顺序无关

线程的调度是由CPU决定,CPU执行子任务时间具有不确定性。

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!