Java多线程同步方法
同步方法: synchronized +方法
和上次的多线程锁synchronized一样,只是将东西封装与方法中
package homework;
//class SellTickets implements Runnable{
// private int tickets=10000;
// Object o=new Object();
// @Override
// public void run(){
// while(true){//synchronized
// synchronized(o) {
//
// if (tickets > 0) {
// try {
// Thread.sleep(1);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// System.out.println(Thread.currentThread().getName() + "购票成功:" + tickets--);
// } else
// break;
// }
// }
// }
//}
class SellTickets implements Runnable{
private static int tickets=1000;
Object o=new Object();
@Override
public void run(){
while(true){//synchronized
// synchronized(o) {
show();
}
}
public static synchronized void show(){//为何写static 因为main方法是定义了三和Sellticks类
{
if (tickets > 0) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "购票成功:" + tickets--);
}
}
}
}
public class test4 {
public static void main(String[] args) {
SellTickets s=new SellTickets();
SellTickets s1=new SellTickets();
SellTickets s2=new SellTickets();
Thread w1=new Thread(s);
Thread w2=new Thread(s1);
Thread w3=new Thread(s2);
w1.setName("窗口一:");
w2.setName("窗口二:");
w3.setName("窗口三:");
w1.start();
w2.start();
w3.start();
}
}