Peterson‘s solution for achieving mutual exclusion

package peterson; public class Peterson { private final int N = 2; //进程数量 private int turn; //现在轮到谁 private boolean[] interested = new boolean[N]; void enter_region(int process) { int other; //其它进程号 other = 1 - process; interested[process] = true;//另一方进程 turn = process; //设置标志 while (turn == process && interested[other] == true) ; //do nothing // System.out.println(process + " is blocked...");// waiting System.out.println(process+" enter.."); } void leave_region(int process) { //进程:谁离开 interested[process] = false; //表示离开临界区 System.out.println(process+" leave.."); } public static void main(String[] args) { // TODO Auto-generated method stub MockProcess m1 = new MockProcess(0); MockProcess m2 = new MockProcess(1); Thread t1 = new Thread(m1); Thread t2 = new Thread(m2); t1.start(); t2.start(); } static Peterson pe = new Peterson(); static class MockProcess implements Runnable { private int process; public MockProcess(int pro) { this.process = pro; } @Override public void run() { pe.enter_region(process); int i = 0; for(; i < 6; i++){ //System.out.println(process + " is working.."); try { Thread.sleep(200); System.out.println( process + " -> " + i); } catch (InterruptedException e) { e.printStackTrace(); } // System.out.println(process + " is leaving.."); } pe.leave_region(process); } } }

你可能感兴趣的:(thread,String,Class)