「Java入門」マルチスレッド で同期コードブロックのサンプルコード

サンプルコード:
public class ThreadStartnews24 {
public static void main(String[] args)
{
ThreadTest t = new ThreadTest();
Thread t1 = new Thread(t);t1.start();
Thread t2 = new Thread(t);t2.start();
Thread t3 = new Thread(t);t3.start();
}
}

class ThreadTest implements Runnable {
private int tickets = 100;
String str = new String(“");

public void run() {
while (true) {
synchronized (str) {
if (tickets > 0) {
try {
Thread.sleep(10);
} catch (Exception e) {
System.out.println(e.getMessage());
}
System.out.println(Thread.currentThread().getName() + “のチェットが売れている" + tickets–);
}
}
}
}
}

Java

Posted by arkgame