Thread:
package com.yzx.demo3;
public class Test extends Thread{
private static int num=100;//总票数
private static Object obj=new Object();
@Override
public void run() {
while (true){
try {
sleep(1000);//所有线程各卖出一张票停留1000毫秒
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (obj){//打开线程锁
if(num>0){
System.out.println(Thread.currentThread().getName() + "出售的票号为:" + num + "的票");
num--;
}else{
System.out.println("票已卖完");
System.exit(0);
}
}
}
}
public static void main(String[] args) {
Test t=new Test();
Thread th=new Thread(t);
th.start();
Test t1=new Test();
Thread th1=new Thread(t);
th1.start();
}
}
Runnable:
package com.yzx.demo3;
import sun.applet.Main;
public class Test2 implements Runnable{
private static int num=100;//总票数
private static Object obj=new Object();
@Override
public void run() {
while (true) {//无限循环
try {
Thread.sleep(1000);//所有线程各卖出一张票停留1000毫秒
synchronized (obj) {//打开线程锁
if (num > 0) {
System.out.println(Thread.currentThread().getName() + "出售的票号为:" + num + "的票");
num--;
} else {
System.out.println("票已卖完");
System.exit(0);
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Test t=new Test();
Thread t1=new Thread(t,"一号窗口");
t1.start();
Thread t2=new Thread(t,"二号窗口");
t2.start();
Thread t3=new Thread(t,"三号窗口");
t3.start();
}
}
Runnable和Thread的区别:
Runnable的实现方式是实现其接口即可
Thread的实现方式是继承其类
Runnable接口支持多继承,但基本上用不到
Thread实现了Runnable接口并进行了扩展,而Thread和Runnable的实质是实现的关系,不是同类东西,所以Runnable或Thread本身没有可比性。