1.使用同步代码块实现
1.1在继承Thread的方式下实现
public class windows extends Thread {
private static int ticket = 100;
@Override
public void run() {
while (true) {
synchronized (windows.class) {
if (ticket > 0) {
System.out.println(getName() + "票号为" + ticket);
ticket--;
} else {
break;
}
}
}
}
public static void main(String[] args) {
windows windows = new windows();
windows windows1 = new windows();
windows windows3 = new windows();
windows.start();
windows1.start();
windows3.start();
}
}
1.2在实现Runnable的方式先实现
public class windows2 implements Runnable {
private int ticket = 100;
@Override
public void run() {
while (true) {
synchronized (this) {
if (ticket > 0) {
System.out.println(Thread.currentThread().getName() + "票号为" + ticket);
ticket--;
} else {
break;
}
}
}
}
public static void main(String[] args) {
windows2 windows = new windows2();
Thread thread = new Thread(windows);
Thread thread2 = new Thread(windows);
Thread thread3 = new Thread(windows);
thread.start();
thread2.start();
thread3.start();
}
}
2.使用同步方法实现
2.1在继承方式实现
public class windows extends Thread {
private static int ticket = 100;
@Override
public void run() {
while (true) {
show();
if(ticket==0){
break;
}
}
}
//为什么这里是静态的,因为要多个对象共用这一个方法这样才能同步
public static synchronized void show(){
if (ticket > 0) {
System.out.println(Thread.currentThread().getName() + "票号为" + ticket);
ticket--;
}
}
public static void main(String[] args) {
windows windows = new windows();
windows windows1 = new windows();
windows windows3 = new windows();
windows.start();
windows1.start();
windows3.start();
}
}
在实现接口方法实现
public class windows2 implements Runnable {
private int ticket = 100;
@Override
public void run() {
while (true) {
show();
if(ticket==0) {
break;
}
}
}
public synchronized void show(){
if (ticket > 0) {
System.out.println(Thread.currentThread().getName() + "票号为" + ticket);
ticket--;
}
}
public static void main(String[] args) {
windows2 windows = new windows2();
Thread thread = new Thread(windows);
Thread thread2 = new Thread(windows);
Thread thread3 = new Thread(windows);
thread.start();
thread2.start();
thread3.start();
}
}