大家都知道,实现多线程有两种方式
1.继承Thread
2.实现 Runnable
而 继承Thread 不好实现我们想要的业务逻辑 所以我们用 实现Runnable 借口来实现我们想要的功能
但是 继承Thread 的代码还是要给大家看的,不多说了,上代码
1.继承Thread
public class Test04 {
public static void main(String[] args) {
new TicketWindow().start();
new TicketWindow().start();
new TicketWindow().start();
new TicketWindow().start();
}
}
class TicketWindow extends Thread {
private int tickets = 10;
public void run() {
while (true) { // 通过死循环语句打印语句
if (tickets > 0) {
Thread th = Thread.currentThread(); // 获取当前线程
String th_name = th.getName(); // 获取当前线程的名字
System.out.println(th_name + " 正在发售第 " + tickets-- + " 张票 ");
}
}
}
}
2.实现 Runnable 接口
package com.kevin;
public class Test05 {
public static void main(String[] args) {
TicketWindow1 task = new TicketWindow1();
new Thread(task,"窗口1").start();
new Thread(task,"窗口2").start();
new Thread(task,"窗口3").start();
new Thread(task,"窗口4").start();
}
}
class TicketWindow1 implements Runnable{
private int tickets = 100;
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
if (tickets > 0) {
Thread thread = Thread.currentThread();
String th_name = thread.getName();
System.out.println(th_name + "正在发售" + tickets-- + "张票");
}
}
}
}
以上就是我的见解了