目录
一. 线程创建
1.继承Thread类 重写run().
class MyThread extends Thread {
@Override
public void run() {
while (true) {
System.out.println("thread");
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Demo1 {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
while (true) {
System.out.println("main");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
2.通过实现Runnable 来实现创建线程.
class MyRunnable implements Runnable {
@Override
public void run() {
while (true) {
System.out.println("thread");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Demo2 {
public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
while (true) {
System.out.println("main");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

这里的话, 就把线程要干的活和线程本身分开了, 使用 runnable 专门来表示 "线程要完成的工作", 把任务提取出来, 就是为了 解耦合 , 上面继承 Thread 的写法就是把线程要完成的工作和线程本身, 耦合在一起了. 而 runnable 这种写法, 只需要把 runnable 传给其他实体就可以了.
3.使用匿名内部类, 来创建 Thread 子类.
// 使用匿名内部类, 来创建 Thread 子类
public static void main(String[] args) {
Thread thread = new Thread() {
@Override
public void run() {
while (true) {
System.out.println("thread");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
thread.start();
}

最低0.47元/天 解锁文章
292

被折叠的 条评论
为什么被折叠?



