线程的实质:即一条道路由单车道变成了多车道,从而避免交通堵塞
方法一:
public class StartRun extends Thread {@Override //线程入口点 public void run() {//线程体 for (int i = 0; i < 20; i++) {System.out.println("2"); } }public static void main(String[] args) {//创建子类的对象 StartRun st=new StartRun();//启动线程 st.start();//thread.run();注意当使用run()方法时,只能按顺序执行,即使它继承了线程 for (int i = 0; i < 20; i++) {System.out.println("1"); } } }
输出的结果只取决与cpu的分配,所以1和2的输出顺序不唯一
方法二
public class StartRun02 implements Runnable {@Override //线程入口点 public void run() {//线程体 for (int i = 0; i < 20; i++) {System.out.println("2"); } }public static void main(String[] args) {//创建实现类对象 StartRun02 thread= new StartRun02();//创建代理类对象 Thread t=new Thread(thread);t.start(); //也可以这样 new Thread(new StartRun02()).start()for (int i = 0; i < 20; i++) {System.out.println("1"); } } }
建议使用方法二——最好使用实现,而不是继承,毕竟继承只能继承一个父类,而实现却可以实现多个接口
本文参考链接:https://www.yisu.com/zixun/540921.html