读书人

多线程跟以及同步Thread,Runable, s

发布时间: 2012-11-01 11:11:31 作者: rapoo

多线程和以及同步,Thread,Runable, synchronized

public class Test {

??? public static void main(String[] args) {

?

??? ??? S run = new S();
??? ??? new Thread(run).start();??????????? //多线程
??? ??? new Thread(run).start();
??? }

?

}

?

class S implements Runnable{
???
??? private int x = 1;
??? private int y = 1;
??? public void run(){
??? ??? for(;;){
??? ??? ??? synchronized(this){???????????????? //如果同步,x始终等于y,2877590:2877590
??? ??? ??? ??? System.out.println(x++ + ":" + y++);? // 如果不同步 出现1934945:1934940,为啥会出现这种情况
??? ??? ??? }
??? ??? }
??? }
}

读书人网 >编程

热点推荐