1. 程式人生 > 其它 >Runnable和Thread的一點區別

Runnable和Thread的一點區別

package Thread.Thread04;

/**
* FileName: TicketDemo
* Author: lps
* Date: 2022/3/30 15:20
* Sign:劉品水 Q:1944900433
*/
public class TicketDemo {
public static void main(String[] args) {
TicketWindow tw = new TicketWindow();
new Thread(tw, "銷售一號").start();
new Thread(tw, "銷售二號").start();
new Thread(tw, "銷售三號").start();




}

static class TicketWindow implements Runnable {
private int ticketNumber=100;
@Override
public void run() {
while (true){
if (ticketNumber>0){
Thread thread = Thread.currentThread();
String threadName = thread.getName();
System.out.println(threadName+"正在銷售第"+ticketNumber--+"張票");
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}

 

 

 

錯誤示範

 

 

package Thread.Thread04;

/**
* FileName: Example01
* Author: lps
* Date: 2022/3/30 15:10
* Sign:劉品水 Q:1944900433
*/
public class Example01 {
public static void main(String[] args) {
new TicketWinodw().start();
new TicketWinodw().start();
new TicketWinodw().start();

}

static class TicketWinodw extends Thread {
private int tickets = 100;

@Override
public void run() {
while (true) {
if (tickets > 0) {
Thread thread = Thread.currentThread();
String tic_name = thread.getName();
System.out.println(tic_name + "正在發行第" + (tickets--) + "張票");

}
}
}
}
}