1. 继承 Thread 类:
private class MyThread extends Thread{
@Override
public void run() {
//doSomething
}
}
MyThread myThread = new MyThread();
myThread.start();
2. 实现 Runnable 接口
private class MyThread implements Runnable{
@Override
public void run() {
//doSomeThing
}
}
Thread myThread = new Thread(new MyThread());
myThread.start();
常用简化模式:
new Thread(new Runnable() {
@Override
public void run() {
//todoList
}
}).start();
不同创建线程区别:
继承方式 不能资源共享, 实现 Runnable可以达到资源共享;
列子「卖票」
package threadTest;
public class TicketRunnable implements Runnable{
private int ticket = 10;
@Override
public void run() {
for(int i =0;i<10;i++){
//添加同步快
synchronized (this){
if(this.ticket>0){
try {
//通过睡眠线程来模拟出最后一张票的抢票场景
Thread.sleep(100);
System.out.println(Thread.currentThread().getName()+"卖票---->"+(this.ticket--));
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
public static void main(String[] arg){
TicketRunnable t1 = new TicketRunnable();
new Thread(t1, "线程1").start();
new Thread(t1, "线程2").start();
}
}