1、具體實現
- 創建線程類 MyThread 繼承 Thread。
- 創建線程對象:MyThread thread1 = new MyThread()。
- 調用線程對象的 start() 方法。
public class ThreadDemo {
public static void main(String[] args) {
MyThread thread1 = new MyThread("線程一");
MyThread thread2 = new MyThread("線程二");
thread1.start();
thread2.start();
}
static class MyThread extends Thread {
// 100 張票
private static int ticket = 100;
public MyThread() {
super();
}
public MyThread(String name) {
super(name);
}
@Override
public void run() {
while (ticket > 0) {
ticket--;
System.out.println(Thread.currentThread() + "賣掉了1張票,剩餘票數爲:" + ticket);
}
}
}
}