Runnable的实现方式更适合来处理多个线程有共享数据的情况
继承Thread类
package Threads;
public class TicketThread extends Thread{
static int number=10;
static Object obj=new Object();
@Override
public void run() {
while(true){
synchronized(obj){
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(number<=0){
break;
}
System.out.println(Thread.currentThread().getName()+":"+(number));
number--;
}
}
}
}
package Threads;
public class Ticketdemo {
public static void main(String[] args) {
TicketThread th1=new TicketThread();
th1.setName("Thread窗口一");
th1.start();
TicketThread th2=new TicketThread();
th2.setName("Thread窗口二");
th2.start();
}
}
实现Runnable接口
package Threads;
public class TicketThread2 implements Runnable {
int number = 10;
@Override
public void run() {
while (true) {
synchronized (this) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (number <= 0) {
break;
}
System.out.println(Thread.currentThread().getName() + ":" + number);
number--;
}
}
}
}
package Threads;
public class Ticketdemo2 {
public static void main(String[] args) {
TicketThread2 t2=new TicketThread2();
Thread th2=new Thread(t2);
Thread th3=new Thread(t2);
th2.setName("Runnable窗口一");
th2.start();;
th3.setName("Runnable窗口二");
th3.start();
}
}