含义
代码执行的索引
使用场景
- 多线程文件下载
- 模拟购票
- 异步任务
创建线程
- 继承Thread
- 实现Runnable
案例
方式一\方式二
。
1、
public class _09Thread {
public static void main(String[] args) {
_09Thread instance = new _09Thread();
}
public _09Thread() {
System.out.println("main方法开始");
//方式一
//Thread firstThread = new FirstThread();
//启动线程
//firstThread.start();
//方式二
Runnable thread = new SecondThread();
Thread secondThread = new Thread(thread);
secondThread.start();
System.out.println("main方法结束");
}
class FirstThread extends Thread{
@Override
public void run() {
super.run();
//比如这是耗时任务
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("当前线程的ID"+getId());
}
}
class SecondThread implements Runnable{
@Override
public void run() {
/*try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
System.out.println("当前线程的ID"+Thread.currentThread().getId());
}
}
}
。
2、购票案例
。
public class _10TicketDemo {
private int ticket = 50;
public static void main(String[] args) {
_10TicketDemo ticketDemo = new _10TicketDemo();
}
public _10TicketDemo() {
Runnable runnable = new BuyThread();
for (int i = 0; i < 3; i++) {
Thread thread = new Thread(runnable, "buy-" + i);
thread.start();
}
}
class BuyThread implements Runnable {
@Override
public void run() {
buy();
}
/*
private void buy() {
synchronized (BuyThread.class) {
while (ticket > 0) {
System.out.println(Thread.currentThread().getName() + "购买了的票号=" + ticket);
ticket--;
}
}
}*/
private void buy() {
while (ticket > 0) {
System.out.println(Thread.currentThread().getName() + "购买了的票号=" + ticket);
ticket--;
}
}
}
}