线程的实现:
1.继承Thread 类,重写run函数
package demo2; public class Demo1 { public static void main(String[] args) { Cat cat = new Cat(); cat.start(); } } class Cat extends Thread { int times = 0; // 重写run函数 public void run() { while (true) { // 每一秒打印一次 try { Thread.sleep(100); } catch (Exception e) { // TODO: handle exception } System.out.println("hello,world"); times++; if (times == 10) break; } } }
2.实现Runable接口,重写run函数
package demo2; public class Demo1 { public static void main(String[] args) { Cat cat = new Cat(); Thread t = new Thread(cat); t.start(); } } class Cat implements Runnable { int times = 0; // 重写run函数 public void run() { while (true) { // 每一秒打印一次 try { Thread.sleep(100); } catch (Exception e) { // TODO: handle exception } System.out.println("hello,world"); times++; if (times == 10) break; } } }
3.多线程运作
原文:https://www.cnblogs.com/helloworld2019/p/10761943.html