使用同步方法解决线程安全问题
实现接口的同步方法实例
package A_ShangGuiGu.Thread.ThreadDemo;
继承的线程的同步方法使用实例
package A_ShangGuiGu.Thread.ThreadDemo;
class Window3 extends Thread{
private static int chepiao = 100;
@Override
public void run() {
while(true){
show();
if (chepiao==0){
break;
}
}
}
private static synchronized void show (){
if (chepiao > 0) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println(Thread.currentThread().getName() + ":" + chepiao);
chepiao--;
}
}
}
public class ThreadWindowTest3 {
public static void main(String[] args) {
Window3 t1 = new Window3();
Window3 t2 = new Window3();
Window3 t3 = new Window3();
t1.setName("窗口1");
t2.setName("窗口2");
t3.setName("窗口3");
t1.start();
t2.start();
t3.start();
}
}