A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

方式1:继承Thread类;

步骤:
1):定义一个类A继承于java.lang.Thread类.
2):在A类中覆盖Thread类中的run方法.
3):我们在run方法中编写需要执行的操作---->run方法里的,线程执行体.
4):在main方法(线程)中,创建线程对象,并启动线程.
创建线程类对象: A类 a = new A类();
调用线程对象的start方法: a.start();//启动一个线程
注意:千万不要调用run方法,如果调用run方法好比是对象调用方法,依然还是只有一个线程,并没有开启新的线程.

public class Thread01 extends Thread {
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println(i);
        }
    }
}

Thread01 t1 = new Thread01();
Thread01 t2 = new Thread01();
t1.start();
t2.start();
1
2
3
4
5
6
7
8
9
10
11
12
13



方式2:实现Runnable接口;

步骤:
1):定义一个类A实现于java.lang.Runnable接口,注意A类不是线程类.
2):在A类中覆盖Runnable接口中的run方法.
3):我们在run方法中编写需要执行的操作---->run方法里的,线程执行体.
4):在main方法(线程)中,创建线程对象,并启动线程.
创建线程类对象: Thread t = new Thread(new A());
调用线程对象的start方法: t.start();
public class MyThread extends OtherClass implements Runnable {  
  public void run() {  
   System.out.println("MyThread.run()");  
  }  
}

MyThread myThread = new MyThread();  
Thread thread = new Thread(myThread);  
thread.start();
1
2
3
4
5
6
7
8
9


使用匿名内部类来创建线程:

只适用于某一个类只使用一次的情况.

public class AnonymousInnerClass {
        public static void main(String[] args) {
                for (int i = 0; i < 33; i++) {
                        System.out.println("打游戏" + i);
                        if (i == 10) {
                                //创建匿名线程对象
                                new Thread() {
                                        public void run() {
                                                for (int j = 0; j < 33; j++) {
                                                        System.out.println("音乐" + j);
                                                }
                                        }
                                }.start();
                        }
                }
        }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class AnonymousInnerClass2 {
        public static void main(String[] args) {
                // 主线程 :运行游戏
                for (int i = 0; i < 33; i++) {
                        System.out.println("打游戏" + i);
                        if (i == 10) {
                                new Thread(new Runnable(){
                                        public void run(){
                                                for (int j = 0; j < 33; j++) {
                                                        System.out.println("==============="+ j);
                                                }
                                        }
                                }).start();                               
                        }
                }
        }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17





---------------------
【转载,仅作分享,侵删】
作者:imxlw00
原文:https://blog.csdn.net/imxlw00/article/details/85330882


1 个回复

倒序浏览
奈斯
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马