JAvaスレッド同期-synchronized
1696 ワード
駅の切符販売事例をシミュレートする
同期コードブロック:public class Ticket implements Runnable{
int tickets = 100;//
Object obj = new Object(); //
@Override
public void run() {
//
while (true) {
synchronized (obj) {
if (tickets > 0) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " " + (tickets--) + " ");
}
}
}
}
}
同期メソッドpublic class Ticket implements Runnable{
int tickets = 100;//
Object obj = new Object(); //
@Override
public void run() {
//
while (true) {
method();
}
}
public synchronized void method(){
if (tickets > 0) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " " + (tickets--) + " ");
}
}
}
テストクラスpublic class TicketTest{public static void main(String args[]){
Ticket t = new Ticket();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
Thread t3 = new Thread(t);
t1.setName(" 1");
t2.setName(" 2");
t3.setName(" 3");
t1.start();
t2.start();
t3.start();
}
}