Join 方法實現是通過wait (小提示:Object 提供的方法)。 當main 線程調用t.join 時候,main 線程會獲得線程對象t 的鎖 (wait 意味著拿到該對象的鎖), 調用該對象的wait( 等待時間) ,直到該對象喚醒main 線程,比如退出後。
這就意味著main 線程調用t.join 時,必須能夠拿到線程t 對象的鎖 ,如果拿不到它是無法wait 的,剛開的例子t.join(1000) 不是說明了main 線程等待1 秒,如果在它等待之前,其他線程擷取了t 對象的鎖,它等待時間可不就是1 毫秒了
執行個體
import java.util.HashMap;
import java.util.regex.Pattern;
/**
* Utilities for String formatting, manipulation, and queries.
* More information about this class is available from <a target="_top" href=
* "http://ostermiller.org/utils/StringHelper.html">ostermiller.org</a>.
*
* @author Stephen Ostermiller http://ostermiller.org/contact.pl?regarding=Java+Utilities
* @since ostermillerutils 1.00.00
*/
public class StringHelper {
/**
* Join all the elements of a string array into a single
* String.
*
* If the given array empty an empty string
* will be returned. Null elements of the array are allowed
* and will be treated like empty Strings.
*
* @param array Array to be joined into a string.
* @return Concatenation of all the elements of the given array.
* @throws NullPointerException if array is null.
*
* @since ostermillerutils 1.05.00
*/
public static String join(String[] array){
return join(array, "");
}
/**
* Join all the elements of a string array into a single
* String.
*
* If the given array empty an empty string
* will be returned. Null elements of the array are allowed
* and will be treated like empty Strings.
*
* @param array Array to be joined into a string.
* @param delimiter String to place between array elements.
* @return Concatenation of all the elements of the given array with the the delimiter in between.
* @throws NullPointerException if array or delimiter is null.
*
* @since ostermillerutils 1.05.00
*/
public static String join(String[] array, String delimiter){
// Cache the length of the delimiter
// has the side effect of throwing a NullPointerException if
// the delimiter is null.
int delimiterLength = delimiter.length();
// Nothing in the array return empty string
// has the side effect of throwing a NullPointerException if
// the array is null.
if (array.length == 0) return "";
// Only one thing in the array, return it.
if (array.length == 1){
if (array[0] == null) return "";
return array[0];
}
// Make a pass through and determine the size
// of the resulting string.
int length = 0;
for (int i=0; i<array.length; i++){
if (array[i] != null) length+=array[i].length();
if (i<array.length-1) length+=delimiterLength;
}
// Make a second pass through and concatenate everything
// into a string buffer.
StringBuffer result = new StringBuffer(length);
for (int i=0; i<array.length; i++){
if (array[i] != null) result.append(array[i]);
if (i<array.length-1) result.append(delimiter);
}
return result.toString();
}
}