Thread 窗口卖票
package com.senior.test;
public class WindowTest {
public static void main(String[] args) {
Window window = new Window();
Window window1 = new Window();
Window window2 = new Window();
window.setName("窗口1");
window1.setName("窗口2");
window2.setName("窗口3");
window.start();
window1.start();
window2.start();
}
}
class Window extends Thread {
private static int ticket = 100;
@Override
public void run() {
while (true) {
if (ticket > 0) {
System.out.println(getName() + "售出:" + ticket);
ticket--;
} else {
break;
}
}
}
}
Runnable窗口卖票
package com.senior.test;
/**
* 创建线程的方式二:实现Runnable接口
* 1、创建一个实现Runnable接口的类
* 2、实现类去实现Runnable中的抽象方法,run()
* 3、创建实现类的对象
* 4、将此对象作为参数传递到Thread类的构造器中,创建Thread对象
* 5、通过Thread类的对象调用start():1、启动线程 2、调用当前线程的run()
*
* 开发中,优先选择,实现runnable接口的方式
* 1、实现的方式没有累的单继承性的局限性
* 2、更适合来处理多个线程有共享数据的情况
*
*
*/
public class RunableTest {
public static void main(String[] args) {
//3、创建实现类的对象
RunThread runThread = new RunThread();
//4、将此对象作为参数传递到Thread类的构造器中,创建Thread类的对象
Thread thread = new Thread(runThread);
thread.setName("线程一");
//5、通过Thread类的对象调用start():1 启动线程 2 调用当前线程的run()-->调用了Runnable类型的target
thread.start();
//再启动一个线程,遍历100以内的偶数
Thread t2 = new Thread(runThread);
t2.setName("线程二");
t2.start();
}
}
class RunThread implements Runnable {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
if (i % 2 == 0) {
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}
}
}