java 线程中String类

String类在java中是不许被重写的

在线程中,也里面的各个方法也是安全的,不会出现易变的情况

如toString这个不会在运行到一半的时候停止的。

 

如下面代码片断

public void run(){
		for(int i = 0 ; i< 10000 ; i++){
			Request request  = requestQueue.getRequest();
			System.out.println(Thread.currentThread().getName() 
					+ " handles " + request );
			try {
				Thread.sleep(random.nextInt(1000));
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

 

public void run(){
		for (int i=0 ; i< 10000 ; i++){
			Request request = new Request("No."+i);
			System.out.println(Thread.currentThread().getName()
					+ " requests "+ request);
			requestQueue.putRequest(request);
			
			try {
				Thread.sleep(random.nextInt(1000));
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

 

 

 在这里面再怎么运行,也不会出现错位的现象

 

Alice requests [ Request No.0 ]
Bobby handles [ Request No.0 ]
Alice requests [ Request No.1 ]
Alice requests [ Request No.2 ]
Bobby handles [ Request No.1 ]
Bobby handles [ Request No.2 ]
Alice requests [ Request No.3 ]
Bobby handles [ Request No.3 ]
Alice requests [ Request No.4 ]
Bobby handles [ Request No.4 ]
Alice requests [ Request No.5 ]
Alice requests [ Request No.6 ]
Bobby handles [ Request No.5 ]
Bobby handles [ Request No.6 ]
Alice requests [ Request No.7 ]
Bobby handles [ Request No.7 ]
Alice requests [ Request No.8 ]

 

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