Skip to content

Instantly share code, notes, and snippets.

@typosone
Created July 2, 2014 07:17
Show Gist options
  • Save typosone/33d6ea1d336491fc2644 to your computer and use it in GitHub Desktop.
Save typosone/33d6ea1d336491fc2644 to your computer and use it in GitHub Desktop.
Java講義 サンプル (すれっど?)
public class BadBank {
// 預金残高
private int value = 0;
// 預け入れ・引き出し
public void addMoney(int money) {
// 現在残高を保存
int currentValue = value;
// 状況表示
System.out.println(Thread.currentThread() + " がaddMoneyに入りました");
// 現在残高を変更
value += money;
// 矛盾がないかどうかチェック
if (currentValue + money != value) {
System.out.println(Thread.currentThread() + " で矛盾が発生!");
System.exit(-1);
}
// 状況表示
System.out.println(Thread.currentThread() + " がaddMoneyから出ました");
}
}
public class BadBankTest {
public static void main(String...args) {
BadBank bank = new BadBank();
new Tester(bank).start();
new Tester(bank).start();
}
}
class Tester extends Thread {
BadBank bank;
public Tester(BadBank bank) {
this.bank = bank;
}
@Override
public void run() {
while (true) {
// 100円預け入れ
bank.addMoney(100);
// 100円引き出し
bank.addMoney(-100);
}
}
}
public class ParallelA {
public static void main(String...args) {
ParallelASub sub = new ParallelASub();
sub.start();
for (int a = 0; a < 10000; a++) {
System.out.println("main: " + a);
}
}
}
class ParallelASub extends Thread {
@Override
public void run() {
for (int a = 0; a < 10000; a++) {
System.out.println("-sub: " + a);
}
}
}
public class ParallelB {
public static void main(String...args) {
ParallelBSub sub = new ParallelBSub();
Thread t = new Thread(sub);
t.start();
for (int b = 0; b < 1000; b++) {
System.out.println("main: " + b);
}
}
}
class ParallelBSub implements Runnable {
@Override
public void run() {
for (int b = 0; b < 1000; b++) {
System.out.println("+sub: " + b);
}
}
}
public class ParallelC {
public static void main(String...args) {
new Thread(new Runnable() {
@Override
public void run() {
for (int c = 0; c < 1000; c++) {
System.out.println("anon: " + c);
}
}
}).start();
for (int c = 0; c < 1000; c++) {
System.out.println("main: " + c);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment