方法1 : 继承Thread类创建多线程
1 package demo06;
2
3 //继承Thread类创建多线程
4 public class ThreadDemo {
5 public static void main(String[] args) throws Exception {
6 SubThread st = new SubThread();
7 //static sleep(long millis) 让当前正在执行的线程休眠millis毫秒
8 Thread.sleep(2000);
9 //设置线程名字
10 st.setName("run线程");
11 //static Thread currentThread() 返回正在执行的线程对象
12 System.out.println(Thread.currentThread().getName());
13 //String getName() 获取线程的名称
14 System.out.println(st.getName());
15 //开启线程
16 st.start();
17 for (int i = 0; i < 50; i++) {
18 System.out.println("main..."+i);
19 }
20
21
22 //匿名内部类创建线程
23 new Thread() {
24 public void run() {
25 System.out.println("!!!");
26 }
27 }.start();
28
29 Runnable r = new Runnable() {
30 public void run() {
31 System.out.println("###");
32 }
33 };
34 new Thread(r).start();
35 }
36 }
1 package demo06;
2
3 public class SubThread extends Thread {
4 public void run() {
5 for (int i = 0; i < 50; i++) {
6 System.out.println("run..."+i);
7 }
8 }
9 }
方法2 : 实现Runnable接口创建多线程
1 package demo06;
2
3 //实现Runnable接口创建多线程
4 public class RunnableDemo {
5 public static void main(String[] args) {
6 SubRunnable sr = new SubRunnable();
7 Thread t = new Thread(sr);
8 t.start();
9 for (int i = 0; i < 50; i++) {
10 System.out.println("main..."+i);
11 }
12 }
13 }
1 package demo06;
2
3 public class SubRunnable implements Runnable {
4 public void run() {
5 for (int i = 0; i < 50; i++) {
6 System.out.println("run..."+i);
7 }
8 }
9 }