实现Runnable方式要比继承Thread方式好
①避免单继承的局限性 ②如果需要多个线程处理同一资源(共享数据),Threrad方式变量需要static修饰
注意:synchronized同步代码块的时候,线程安全地问题,所有的线程需要共用一把锁
package com.shn.juc.thread;
// 模拟火车站售票窗口:三个窗口一共100张票
public class WindowsSaleTicket {
public static void main(String[] args) {
int tickets = 10;
SubWindowThread subWindowThread1 = new SubWindowThread();
SubWindowThread subWindowThread2 = new SubWindowThread();
SubWindowThread subWindowThread3 = new SubWindowThread();
subWindowThread1.setName("窗口1");
subWindowThread2.setName("窗口2");
subWindowThread3.setName("窗口3");
subWindowThread1.start();
subWindowThread2.start();
subWindowThread3.start();
}
}
class SubWindowThread extends Thread{
static int tickets=10;//剩余票数,三个窗口公用,所以需要用static修饰,成为类变量
static Object obj = new Object();
public void run(){
while(true){
synchronized(obj){
if(tickets>0){
try {
Thread.currentThread().sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"---"+tickets--);
}else{
break;
}
}
}
}
}
package com.shn.juc.thread;
public class ImplementRunnableClass {
public static void main(String[] args) {
SubWindow sw = new SubWindow();
Thread t1 = new Thread(sw);
Thread t2 = new Thread(sw);
Thread t3 = new Thread(sw);
t1.start();
t2.start();
t3.start();
}
}
class SubWindow implements Runnable{
int tickets=10;//剩余票数,三个窗口公用,共享数据
Object obj = new Object();//三个线程共享的锁,成员变量
public void run(){
// Object obj = new Object();//局部变量,各个线程各自的锁,失效
while(true){
synchronized(obj){
if(tickets>0){
try {
Thread.currentThread().sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"---"+tickets--);
}else{
break;
}
}
}
}
}