public class ThreadTest { private volatile static int count=0; private volatile static int flag=0; private static void add(){ for(int i=0;i<1e7;i++){ count=count+1; } } public static void main(String[] args) { Thread t1=new Thread(new Runnable() { @Override public void run() { //lock while(flag==1){ System.out.print("."); } flag=1; //临界区 add(); //unlock flag=0; } }); Thread t2=new Thread(new Runnable() { @Override public void run() { //lock while(flag==1){ System.out.print("."); } flag=1; //临界区 add(); //unlock flag=0; } }); t1.start(); t2.start(); System.out.println(count); } }
全部评论
(2) 回帖