一、创建线程的两种方式
1.继承Thread类,重写run方法
public class MyThread extends Thread { private int i = 0; @Override public void run() { for (; i < 10; i++) { System.out.println(getName() + " " + i); } } }
2.实现runable接口,重写run方法
2.1.实现runnable即可
public class MyRunnable implements Runnable { private int i; @Override public void run() { for (; i < 10; i++) { System.out.println(Thread.currentThread().getName() + " " + i); } } }
2.2.实现callabble接口
public class MyCallable implements Callable { private int i = 0; @Override public Object call() throws Exception { for (; i < 10; i++) { System.out.println(Thread.currentThread().getName() + " " + i); } return null; } }
综上main方法
public class KangTest { public static void main(String[] args) { for (int i = 0; i < 10; i++) { Thread thread1 = new MyThread(); thread1.start(); } for (int i = 0; i < 10; i++) { Thread thread = new Thread(new MyRunnable(), "MyRunnable" + i); thread.start(); } for (int i = 0; i < 10; i++) { FutureTask futureTask = new FutureTask(new MyCallable()); Thread thread = new Thread(futureTask, "futureTask" + i); thread.start(); } } }
二、线程的生命周期
1.线程的状态
2.状态流转
3.线程启动方法源码
Thread#start()源码分析
参考:图灵学院相关教材
参考:https://blog.csdn.net/yangyechi/article/details/88195068
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)