Xu Hướng 11/2022 ❤️ Hướng Dẫn Sử Dụng Biểu Thức Chính Quy Trong Java ❣️ Top View | Channuoithuy.edu.vn

Bạn đang xem bài viết Hướng Dẫn Sử Dụng Biểu Thức Chính Quy Trong Java được cập nhật mới nhất trên website Channuoithuy.edu.vn. Hy vọng những thông tin mà chúng tôi đã chia sẻ là hữu ích với bạn. Nếu nội dung hay, ý nghĩa bạn hãy chia sẻ với bạn bè của mình và luôn theo dõi, ủng hộ chúng tôi để cập nhật những thông tin mới nhất.

1- Regular expression

Một biểu thức chính quy (Regular expressions) định nghĩa một khuôn mẫu (pattern) tìm kiếm chuỗi. Nó có thể được sử dụng tìm kiếm, sửa đổi, và thao tác trên văn bản. Khuôn mẫu được định nghĩa bởi biểu thức chính quy có thể khớp một hoặc một vài lần, hoặc không khớp với một văn bản cho trước.

Viết tắt của biểu thức chính quy là regex

Biểu thức chính quy (Regular expression) được hỗ trợ bởi hầu hết các ngôn ngữ lập trình, ví dụ, Java, C#, C/C++, v..v Thật không may mỗi ngôn ngữ hỗ trợ biểu thức thông thường hơi khác nhau.

2- Quy tắc viết biểu thức chính quy

TT Biểu thức chính quy Mô tả

1 . Khớp (match) với bất kỳ ký tự nào

2 ^regex Biểu thức chính quy phải  khớp tại điểm bắt đầu

3 regex$ Biểu thức chính quy phải khớp ở cuối dòng.

4 [abc] Thiết lập định nghĩa, có thể khớp với a hoặc b hoặc c.

5 [abc][vz] Thiết lập định nghĩa, có thể khớp với a hoặc b hoặc c theo sau là v hay z.

6 [^abc] Khi dấu ^ xuất hiện như là nhân vật đầu tiên trong dấu ngoặc vuông, nó phủ nhận mô hình. Điều này có thể khớp với bất kỳ ký tự nào ngoại trừ a hoặc b hoặc c.

7 [a-d1-7] Phạm vi: phù hợp với một chuỗi giữa a và điểm d và con số từ 1 đến 7.

8 Tìm X hoặc Z.

9 XZ Tìm X và theo sau là Z.

10 $ Kiểm tra kết thúc dòng.

 

11 d Số bất kỳ, viết ngắn gọn cho [0-9]

12 D Ký tự không phải là số, viết ngắn gon cho [^0-9]

13 s Ký tự khoảng trắng, viết ngắn gọn cho [ tnx0brf]

14 S Ký tự không phải khoản trắng, viết ngắn gọn cho [^s]

15 w Ký tự chữ, viết ngắn gọn cho [a-zA-Z_0-9]

16 W Ký tự không phải chữ, viết ngắn gọn cho [^w]

17 S+ Một số ký tự không phải khoảng trắng (Một hoặc nhiều)

18 b Ký tự thuộc a-z hoặc A-Z hoặc 0-9 hoặc _, viết ngắn gọn cho [a-zA-Z0-9_].

 

19 * Xuất hiện 0 hoặc nhiều lần, viết ngắn gọn cho {0,}

20 + Xuất hiện 1 hoặc nhiều lần, viết ngắn gọn cho {1,}

21 ? Xuất hiện 0 hoặc 1 lần, ? viết ngắn gọn cho {0,1}.

22 {X} Xuất hiện X lần, {}

23 {X,Y} Xuất hiện trong khoảng X tới Y lần.

24 *? * có nghĩa là xuất hiện 0 hoặc nhiều lần, thêm ? phía sau nghĩa là tìm kiếm khớp nhỏ nhất.

3- Các ký tự đặc biệt trong Java Regex (Special characters)

Một số ký tự đặc biệt trong Java Regex:

Những ký tự liệt kê ở trên là các ký tự đặc biệt. Trong Java Regex bạn muốn nó hiểu các ký tự đó theo cách thông thường bạn cần thêm dấu ở phía trước.

Chẳng hạn ký tự chấm . java regex đang hiểu là một ký tự bất kỳ, nếu bạn muốn nó hiểu là một ký tự chấm thông thường, cần phải có dấu phía trước.

String regex = “.”; String regex = “\.”;

String regex = “.”; String regex = “\.”;

4- Sử dụng String.matches(String)

Class String

… public boolean matches(String regex) ..

… public boolean matches(String regex) ..

Sử dụng  method String.matches(String regex) cho phép bạn kiểm tra toàn bộ String có khớp với một regex hay không. Đây là một cách thông dụng nhất. Hãy xem các ví dụ:

StringMatches.java

package org.o7planning.tutorial.regex.stringmatches; public class StringMatches { public static void main(String[] args) { String s1 = “a”; System.out.println(“s1=” + s1); boolean match = s1.matches(“.”); System.out.println(“-Match . ” + match); s1 = “abc”; System.out.println(“s1=” + s1); match = s1.matches(“.”); System.out.println(“-Match . ” + match); match = s1.matches(“.*”); System.out.println(“-Match .* ” + match); String s2 = “m”; System.out.println(“s2=” + s2); match = s2.matches(“^m”); System.out.println(“-Match ^m ” + match); s2 = “mnp”; System.out.println(“s2=” + s2); match = s2.matches(“^m”); System.out.println(“-Match ^m ” + match); match = s2.matches(“^m.+”); System.out.println(“-Match ^m.+ ” + match); String s3 = “p”; System.out.println(“s3=” + s3); match = s3.matches(“p$”); System.out.println(“-Match p$ ” + match); s3 = “2nnp”; System.out.println(“s3=” + s3); match = s3.matches(“p$”); System.out.println(“-Match p$ ” + match); match = s3.matches(“.n{1,3}p$”); System.out.println(“-Match .n{1,3}p$ ” + match); String s4 = “2ybcd”; System.out.println(“s4=” + s4); match = s4.matches(“2[xyz].+”); System.out.println(“-Match 2[xyz].+ ” + match); String s5 = “2bkbv”; match = s5.matches(“.+[abc][zv].*”); System.out.println(“-Match .+[abc][zv].* ” + match); } }

package org.o7planning.tutorial.regex.stringmatches; public class StringMatches { public static void main(String[] args) { String s1 = “a”; System.out.println(“s1=” + s1); boolean match = s1.matches(“.”); System.out.println(“-Match . ” + match); s1 = “abc”; System.out.println(“s1=” + s1); match = s1.matches(“.”); System.out.println(“-Match . ” + match); match = s1.matches(“.*”); System.out.println(“-Match .* ” + match); String s2 = “m”; System.out.println(“s2=” + s2); match = s2.matches(“^m”); System.out.println(“-Match ^m ” + match); s2 = “mnp”; System.out.println(“s2=” + s2); match = s2.matches(“^m”); System.out.println(“-Match ^m ” + match); match = s2.matches(“^m.+”); System.out.println(“-Match ^m.+ ” + match); String s3 = “p”; System.out.println(“s3=” + s3); match = s3.matches(“p$”); System.out.println(“-Match p$ ” + match); s3 = “2nnp”; System.out.println(“s3=” + s3); match = s3.matches(“p$”); System.out.println(“-Match p$ ” + match); match = s3.matches(“.n{1,3}p$”); System.out.println(“-Match .n{1,3}p$ ” + match); String s4 = “2ybcd”; System.out.println(“s4=” + s4); match = s4.matches(“2[xyz].+”); System.out.println(“-Match 2[xyz].+ ” + match); String s5 = “2bkbv”; match = s5.matches(“.+[abc][zv].*”); System.out.println(“-Match .+[abc][zv].* ” + match); } }

Kết quả chạy ví dụ:

s1=a -Match . true s1=abc -Match . false -Match .* true s2=m -Match ^m true s2=mnp -Match ^m false -Match ^m.+ true s3=p -Match p$ true s3=2nnp -Match p$ false -Match .n{1,3}p$ true s4=2ybcd -Match 2[xyz].+ true -Match .+[abc][zv].* true

s1=a -Match . true s1=abc -Match . false -Match .* true s2=m -Match ^m true s2=mnp -Match ^m false -Match ^m.+ true s3=p -Match p$ true s3=2nnp -Match p$ false -Match .n{1,3}p$ true s4=2ybcd -Match 2[xyz].+ true -Match .+[abc][zv].* true

SplitWithRegex.java

package org.o7planning.tutorial.regex.stringmatches; public class SplitWithRegex { public static final String TEXT = “This is my text”; public static void main(String[] args) { System.out.println(“TEXT=” + TEXT); String regex = “\s+”; String[] splitString = TEXT.split(regex); System.out.println(splitString.length); for (String string : splitString) { System.out.println(string); } String newText = TEXT.replaceAll(“\s+”, “t”); System.out.println(“New text=” + newText); } }

package org.o7planning.tutorial.regex.stringmatches; public class SplitWithRegex { public static final String TEXT = “This is my text”; public static void main(String[] args) { System.out.println(“TEXT=” + TEXT); String regex = “\s+”; String[] splitString = TEXT.split(regex); System.out.println(splitString.length); for (String string : splitString) { System.out.println(string); } String newText = TEXT.replaceAll(“\s+”, “t”); System.out.println(“New text=” + newText); } }

Kết quả chạy ví dụ:

TEXT=This is my text 4 This is my text New text=This is my text

TEXT=This is my text 4 This is my text New text=This is my text

EitherOrCheck.java

package org.o7planning.tutorial.regex.stringmatches; public class EitherOrCheck { public static void main(String[] args) { String s = “The film Tom and Jerry!”; System.out.println(“s=” + s); s = “The cat”; System.out.println(“s=” + s); s = “The Tom cat”; System.out.println(“s=” + s); } }

package org.o7planning.tutorial.regex.stringmatches; public class EitherOrCheck { public static void main(String[] args) { String s = “The film Tom and Jerry!”; System.out.println(“s=” + s); s = “The cat”; System.out.println(“s=” + s); s = “The Tom cat”; System.out.println(“s=” + s); } }

Kết quả chạy ví dụ:

s=The film Tom and Jerry! s=The cat s=The Tom cat

s=The film Tom and Jerry! s=The cat s=The Tom cat

5- Sử dụng Pattern và Matcher

1. Pattern là một đối tượng mẫu, một phiên bản đã được biên dịch của một biểu thức chính quy. Nó không có cấu tử (constructor) public, và chúng ta sẽ sử dụng method tĩnh compile(String) để tạo đối tượng, với tham số là biểu thức chính quy.

2. Matcher là một phương tiện để so khớp chuỗi dữ liệu đầu vào với đối tượng Pattern đã được tạo ra ở trên. Class này không có cấu tử public, và chúng ta lấy đối tượng này thông qua method matcher(String) của đối tượng Pattern. Với tham số đầu vào String là văn bản cần kiểm tra.

3. PatternSyntaxException sẽ bị ném ra nếu biểu thức chính quy có ngữ pháp không chính xác.

String regex= “.xx.”; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(“MxxY”); boolean match = matcher.matches(); System.out.println(“Match “+ match);

String regex= “.xx.”; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(“MxxY”); boolean match = matcher.matches(); System.out.println(“Match “+ match);

Class Pattern:

public static Pattern compile(String regex, int flags) ; public static Pattern compile(String regex); public Matcher matcher(CharSequence input); public static boolean matches(String regex, CharSequence input);

public static Pattern compile(String regex, int flags) ; public static Pattern compile(String regex); public Matcher matcher(CharSequence input); public static boolean matches(String regex, CharSequence input);

Class Matcher:

public int start() public int start(int group) public int end() public int end(int group) public String group() public String group(int group) public String group(String name) public int groupCount() public boolean matches() public boolean lookingAt() public boolean find()

public int start() public int start(int group) public int end() public int end(int group) public String group() public String group(int group) public String group(String name) public int groupCount() public boolean matches() public boolean lookingAt() public boolean find()

Đây là một ví dụ sử dụng Matcher và method find() để tìm kiếm các chuỗi con khớp với một biểu thức chính quy.

MatcherFind.java

package org.o7planning.tutorial.regex; import java.util.regex.Matcher; import java.util.regex.Pattern; public class MatcherFind { public static void main(String[] args) { final String TEXT = “This t is a ttt String”; String regex = “\s+”; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(TEXT); int i = 0; while (matcher.find()) { System.out.print(“start” + i + ” = ” + matcher.start()); System.out.print(” end” + i + ” = ” + matcher.end()); System.out.println(” group” + i + ” = ” + matcher.group()); i++; } } }

package org.o7planning.tutorial.regex; import java.util.regex.Matcher; import java.util.regex.Pattern; public class MatcherFind { public static void main(String[] args) { final String TEXT = “This t is a ttt String”; String regex = “\s+”; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(TEXT); int i = 0; while (matcher.find()) { System.out.print(“start” + i + ” = ” + matcher.start()); System.out.print(” end” + i + ” = ” + matcher.end()); System.out.println(” group” + i + ” = ” + matcher.group()); i++; } } }

Kết quả chạy ví dụ:

start = 4 end = 7 group = start = 9 end = 10 group = start = 11 end = 16 group =

start = 4 end = 7 group = start = 9 end = 10 group = start = 11 end = 16 group =

Method Matcher.lookingAt()

MatcherLookingAt.java

package org.o7planning.tutorial.regex; import java.util.regex.Matcher; import java.util.regex.Pattern; public class MatcherLookingAt { public static void main(String[] args) { String country1 = “iran”; String country2 = “Iraq”; String regex = “^I.[ae]”; Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(country1); System.out.println(“lookingAt = ” + matcher.lookingAt()); System.out.println(“matches = ” + matcher.matches()); matcher.reset(country2); System.out.println(“lookingAt = ” + matcher.lookingAt()); System.out.println(“matches = ” + matcher.matches()); } }

package org.o7planning.tutorial.regex; import java.util.regex.Matcher; import java.util.regex.Pattern; public class MatcherLookingAt { public static void main(String[] args) { String country1 = “iran”; String country2 = “Iraq”; String regex = “^I.[ae]”; Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(country1); System.out.println(“lookingAt = ” + matcher.lookingAt()); System.out.println(“matches = ” + matcher.matches()); matcher.reset(country2); System.out.println(“lookingAt = ” + matcher.lookingAt()); System.out.println(“matches = ” + matcher.matches()); } }

6- Nhóm (Group)

Một biểu thức chính quy bạn có thể tách ra thành các nhóm (group):

String regex = “\s+=\d+”; String regex2 = “(\s+)(=)(\d+)”; String regex3 = “(\s+)(=\d+)”;

String regex = “\s+=\d+”; String regex2 = “(\s+)(=)(\d+)”; String regex3 = “(\s+)(=\d+)”;

Chú ý: Sử dụng (?:pattern) để thông báo với Java không xem đây là một group (None-capturing group)

Nhóm bắt theo tên cũng có thể được truy cập thông qua Matcher.group(int group) với cách đánh chỉ số tương tự.

Nội bộ, Java chỉ lập bản đồ (ánh xạ) từ tên đến chỉ số nhóm. Do đó, bạn không thể sử dụng cùng tên để bắt 2 nhóm khác nhau.

NamedGroup.java

package org.o7planning.tutorial.regex; import java.util.regex.Matcher; import java.util.regex.Pattern; public class NamedGroup { public static void main(String[] args) { final String TEXT = ” int a = 100;float b= 130;float c= 110 ; “; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(TEXT); while (matcher.find()) { String group = matcher.group(); System.out.println(group); System.out.println(“declare: ” + matcher.group(“declare”)); System.out.println(“value: ” + matcher.group(“value”)); } } }

package org.o7planning.tutorial.regex; import java.util.regex.Matcher; import java.util.regex.Pattern; public class NamedGroup { public static void main(String[] args) { final String TEXT = ” int a = 100;float b= 130;float c= 110 ; “; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(TEXT); while (matcher.find()) { String group = matcher.group(); System.out.println(group); System.out.println(“declare: ” + matcher.group(“declare”)); System.out.println(“value: ” + matcher.group(“value”)); } } }

Kết quả chạy ví dụ:

int a = 100; declare: int a value: 100 —————————— float b= 130; declare: float b value: 130 —————————— float c= 110 ; declare: float c value: 110 ——————————

int a = 100; declare: int a value: 100 —————————— float b= 130; declare: float b value: 130 —————————— float c= 110 ; declare: float c value: 110 ——————————

7- Sử dụng Pattern, Matcher, Group và *?

Trong một số tình huống *? rất quan trọng, hãy xem một ví dụ sau:

*? sẽ tìm ra một phù hợp nhỏ nhất. Chúng ta xem ví dụ sau:

NamedGroup2.java

package org.o7planning.tutorial.regex; import java.util.regex.Matcher; import java.util.regex.Pattern; public class NamedGroup2 { public static void main(String[] args) { Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(TEXT); while (matcher.find()) { System.out.println(“File Name = ” + matcher.group(“fileName”)); } } }

package org.o7planning.tutorial.regex; import java.util.regex.Matcher; import java.util.regex.Pattern; public class NamedGroup2 { public static void main(String[] args) { Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(TEXT); while (matcher.find()) { System.out.println(“File Name = ” + matcher.group(“fileName”)); } } }

Kết quả chạy ví dụ:

File Name = FILE1 File Name = FILE2

File Name = FILE1 File Name = FILE2

Trong .NET Framework, System.DateTime là một class đại diện cho ngày tháng và thời gian, giá trị của nó nằm trong khoảng 12:00:00 đêm ngày 01-01-0001 tới 11:59:59 tối ngày 31-12-9999.

Có nhiều phương thức khởi tạo (constructor) để bạn khởi tạo một đối tượng DateTime.

Now là một thuộc tính tĩnh của DateTime nó trả về đối tượng DateTime mô tả thời điểm hiện tại.

DateTime now = DateTime.Now; Console.WriteLine(“Now is “+ now); Thuộc tính Kiểu dữ liệu Mô tả

DateTime now = DateTime.Now; Console.WriteLine(“Now is “+ now); Thuộc tính Kiểu dữ liệu Mô tả

Ticks

long

Lấy ra số lượng “tick” được đại diện bởi đối tượng này. (1 phút = 600 triệu tick)

DateTime cung cấp các phương thức cho phép bạn thêm, hoặc trừ một khoảng thời gian. TimeSpan là một class chứa thông tin một khoảng thời gian, nó có thể tham gia như một tham số trong các phương thức thêm bớt thời gian của DateTime.

Class DateTime cũng có các phương thức cho phép thêm bớt một loại đơn vị thời gian chẳng hạn:

AddYears

AddDays

AddMinutes

Bạn có hai đối tượng DateTime, bạn có thể tính được khoảng thời gian giữa 2 đối tượng này, kết quả nhận được là một đối tượng TimeSpan.

DateTime có một phương thức tĩnh làCompare. Phương thức dùng để so sánh 2 đối tượng DateTime xem đối tượng nào sớm hơn đối tượng còn lại:

public static int Compare(DateTime firstDateTime, DateTime secondDateTime);

public static int Compare(DateTime firstDateTime, DateTime secondDateTime);

Định dạng DateTime nghĩa là chuyển đổi đối tượng DateTime thành một string theo một khuôn mẫu nào đó, chẳng hạn theo định dạng ngày/tháng/năm, … hoặc định dạng dựa vào địa phương (locale) cụ thể.

Phương thức GetDateTimeFormats của DateTime:

Chuyển đổi giá trị của đối tượng này (DateTime) thành một mảng các string đã định dạng theo các chuẩn được hỗ trợ.

Ví dụ trên liệt kê ra các string sau khi định dạng một đối tượng DateTime theo các tiêu chuẩn có sẵn được hỗ trợ bởi.NET. Để lấy định dạng theo một mẫu cụ thể bạn sử dụng một trong các phương thức sau:

Phương thứcMô tả

Phương thứcMô tả

ToString(String, IFormatProvider)

Chuyển đổi các giá trị của đối tượng DateTime hiện tại thành string đại diện tương đương của nó bằng cách sử dụng định dạng cho bởi tham số String, và các thông tin định dạng văn hóa (Culture) cho bởi tham số IFormatProvider.

ToString(IFormatProvider)

Chuyển đổi giá trị của đối tượng DateTime hiện tại thành một string tương ứng với thông tin định dạng văn hóa (Culture) cho bởi tham số IFormatProvider.

ToString(String)

Chuyển đổi các giá trị của đối tượng DateTime hiện tại thành một string tương đương của nó bằng cách sử dụng định dạng cho bởi tham số String và các quy ước định dạng của nền văn hóa hiện tại.

Các ký tự định dạng tiêu chuẩn.

CodePattern

CodePattern

“d”

Ngày tháng năm ngắn

“D”

Ngày tháng năm dài

“f”

Ngày tháng năm dài, thời gian ngắn

“F”

Ngày tháng năm dài, thời gian dài.

“g”

Ngày tháng thời gian nói chung. Thời gian ngắn.

“G”

Ngày tháng thời gian nói chung. Thời gian dài.

“M”, ‘m”

Tháng/ngày.

“O”, “o”

Round-trip date/time.

“R”, “r”

RFC1123

“s”

Ngày tháng thời gian có thể sắp xếp

“t”

Thời gian ngắn

“T”

Thời gian dài

“u”

Ngày tháng năm có thể sắp xếp, phổ biến (Universal sortable date time).

“U”

Ngày tháng năm thời gian dài, phổ biến (Universal full date time).

“Y”, “y”

Năm tháng

======d ======== 12/20/2015 12/20/15 12/20/15 12/20/2015 15/12/20 2015-12-20 20-Dec-15 ======D ======== Sunday, December 20, 2015 December 20, 2015 Sunday, 20 December, 2015 20 December, 2015 ======f ======== Sunday, December 20, 2015 11:30 AM Sunday, December 20, 2015 11:30 AM Sunday, December 20, 2015 11:30 Sunday, December 20, 2015 11:30 December 20, 2015 11:30 AM December 20, 2015 11:30 AM December 20, 2015 11:30 December 20, 2015 11:30 Sunday, 20 December, 2015 11:30 AM Sunday, 20 December, 2015 11:30 AM Sunday, 20 December, 2015 11:30 Sunday, 20 December, 2015 11:30 20 December, 2015 11:30 AM 20 December, 2015 11:30 AM 20 December, 2015 11:30 20 December, 2015 11:30 ======F ======== Sunday, December 20, 2015 11:30:50 AM Sunday, December 20, 2015 11:30:50 AM Sunday, December 20, 2015 11:30:50 Sunday, December 20, 2015 11:30:50 December 20, 2015 11:30:50 AM December 20, 2015 11:30:50 AM December 20, 2015 11:30:50 December 20, 2015 11:30:50 Sunday, 20 December, 2015 11:30:50 AM Sunday, 20 December, 2015 11:30:50 AM Sunday, 20 December, 2015 11:30:50 Sunday, 20 December, 2015 11:30:50 20 December, 2015 11:30:50 AM 20 December, 2015 11:30:50 AM 20 December, 2015 11:30:50 20 December, 2015 11:30:50 ======g ======== 12/20/2015 11:30 AM 12/20/2015 11:30 AM 12/20/2015 11:30 12/20/2015 11:30 12/20/15 11:30 AM 12/20/15 11:30 AM 12/20/15 11:30 12/20/15 11:30 12/20/15 11:30 AM 12/20/15 11:30 AM 12/20/15 11:30 12/20/15 11:30 12/20/2015 11:30 AM 12/20/2015 11:30 AM 12/20/2015 11:30 12/20/2015 11:30 15/12/20 11:30 AM 15/12/20 11:30 AM 15/12/20 11:30 15/12/20 11:30 2015-12-20 11:30 AM 2015-12-20 11:30 AM 2015-12-20 11:30 2015-12-20 11:30 20-Dec-15 11:30 AM 20-Dec-15 11:30 AM 20-Dec-15 11:30 20-Dec-15 11:30 ======G ======== 12/20/2015 11:30:50 AM 12/20/2015 11:30:50 AM 12/20/2015 11:30:50 12/20/2015 11:30:50 12/20/15 11:30:50 AM 12/20/15 11:30:50 AM 12/20/15 11:30:50 12/20/15 11:30:50 12/20/15 11:30:50 AM 12/20/15 11:30:50 AM 12/20/15 11:30:50 12/20/15 11:30:50 12/20/2015 11:30:50 AM 12/20/2015 11:30:50 AM 12/20/2015 11:30:50 12/20/2015 11:30:50 15/12/20 11:30:50 AM 15/12/20 11:30:50 AM 15/12/20 11:30:50 15/12/20 11:30:50 2015-12-20 11:30:50 AM 2015-12-20 11:30:50 AM 2015-12-20 11:30:50 2015-12-20 11:30:50 20-Dec-15 11:30:50 AM 20-Dec-15 11:30:50 AM 20-Dec-15 11:30:50 20-Dec-15 11:30:50 ======M ======== December 20 ======m ======== December 20 ======O ======== 2015-12-20T11:30:50.0000000 ======o ======== 2015-12-20T11:30:50.0000000 ======R ======== ======r ======== ======s ======== 2015-12-20T11:30:50 ======t ======== 11:30 AM 11:30 AM 11:30 11:30 ======T ======== 11:30:50 AM 11:30:50 AM 11:30:50 11:30:50 ======u ======== 2015-12-20 11:30:50Z ======U ======== Sunday, December 20, 2015 4:30:50 AM Sunday, December 20, 2015 04:30:50 AM Sunday, December 20, 2015 4:30:50 Sunday, December 20, 2015 04:30:50 December 20, 2015 4:30:50 AM December 20, 2015 04:30:50 AM December 20, 2015 4:30:50 December 20, 2015 04:30:50 Sunday, 20 December, 2015 4:30:50 AM Sunday, 20 December, 2015 04:30:50 AM Sunday, 20 December, 2015 4:30:50 Sunday, 20 December, 2015 04:30:50 20 December, 2015 4:30:50 AM 20 December, 2015 04:30:50 AM 20 December, 2015 4:30:50 20 December, 2015 04:30:50 ======Y ======== December, 2015 ======y ======== December, 2015

======d ======== 12/20/2015 12/20/15 12/20/15 12/20/2015 15/12/20 2015-12-20 20-Dec-15 ======D ======== Sunday, December 20, 2015 December 20, 2015 Sunday, 20 December, 2015 20 December, 2015 ======f ======== Sunday, December 20, 2015 11:30 AM Sunday, December 20, 2015 11:30 AM Sunday, December 20, 2015 11:30 Sunday, December 20, 2015 11:30 December 20, 2015 11:30 AM December 20, 2015 11:30 AM December 20, 2015 11:30 December 20, 2015 11:30 Sunday, 20 December, 2015 11:30 AM Sunday, 20 December, 2015 11:30 AM Sunday, 20 December, 2015 11:30 Sunday, 20 December, 2015 11:30 20 December, 2015 11:30 AM 20 December, 2015 11:30 AM 20 December, 2015 11:30 20 December, 2015 11:30 ======F ======== Sunday, December 20, 2015 11:30:50 AM Sunday, December 20, 2015 11:30:50 AM Sunday, December 20, 2015 11:30:50 Sunday, December 20, 2015 11:30:50 December 20, 2015 11:30:50 AM December 20, 2015 11:30:50 AM December 20, 2015 11:30:50 December 20, 2015 11:30:50 Sunday, 20 December, 2015 11:30:50 AM Sunday, 20 December, 2015 11:30:50 AM Sunday, 20 December, 2015 11:30:50 Sunday, 20 December, 2015 11:30:50 20 December, 2015 11:30:50 AM 20 December, 2015 11:30:50 AM 20 December, 2015 11:30:50 20 December, 2015 11:30:50 ======g ======== 12/20/2015 11:30 AM 12/20/2015 11:30 AM 12/20/2015 11:30 12/20/2015 11:30 12/20/15 11:30 AM 12/20/15 11:30 AM 12/20/15 11:30 12/20/15 11:30 12/20/15 11:30 AM 12/20/15 11:30 AM 12/20/15 11:30 12/20/15 11:30 12/20/2015 11:30 AM 12/20/2015 11:30 AM 12/20/2015 11:30 12/20/2015 11:30 15/12/20 11:30 AM 15/12/20 11:30 AM 15/12/20 11:30 15/12/20 11:30 2015-12-20 11:30 AM 2015-12-20 11:30 AM 2015-12-20 11:30 2015-12-20 11:30 20-Dec-15 11:30 AM 20-Dec-15 11:30 AM 20-Dec-15 11:30 20-Dec-15 11:30 ======G ======== 12/20/2015 11:30:50 AM 12/20/2015 11:30:50 AM 12/20/2015 11:30:50 12/20/2015 11:30:50 12/20/15 11:30:50 AM 12/20/15 11:30:50 AM 12/20/15 11:30:50 12/20/15 11:30:50 12/20/15 11:30:50 AM 12/20/15 11:30:50 AM 12/20/15 11:30:50 12/20/15 11:30:50 12/20/2015 11:30:50 AM 12/20/2015 11:30:50 AM 12/20/2015 11:30:50 12/20/2015 11:30:50 15/12/20 11:30:50 AM 15/12/20 11:30:50 AM 15/12/20 11:30:50 15/12/20 11:30:50 2015-12-20 11:30:50 AM 2015-12-20 11:30:50 AM 2015-12-20 11:30:50 2015-12-20 11:30:50 20-Dec-15 11:30:50 AM 20-Dec-15 11:30:50 AM 20-Dec-15 11:30:50 20-Dec-15 11:30:50 ======M ======== December 20 ======m ======== December 20 ======O ======== 2015-12-20T11:30:50.0000000 ======o ======== 2015-12-20T11:30:50.0000000 ======R ======== ======r ======== ======s ======== 2015-12-20T11:30:50 ======t ======== 11:30 AM 11:30 AM 11:30 11:30 ======T ======== 11:30:50 AM 11:30:50 AM 11:30:50 11:30:50 ======u ======== 2015-12-20 11:30:50Z ======U ======== Sunday, December 20, 2015 4:30:50 AM Sunday, December 20, 2015 04:30:50 AM Sunday, December 20, 2015 4:30:50 Sunday, December 20, 2015 04:30:50 December 20, 2015 4:30:50 AM December 20, 2015 04:30:50 AM December 20, 2015 4:30:50 December 20, 2015 04:30:50 Sunday, 20 December, 2015 4:30:50 AM Sunday, 20 December, 2015 04:30:50 AM Sunday, 20 December, 2015 4:30:50 Sunday, 20 December, 2015 04:30:50 20 December, 2015 4:30:50 AM 20 December, 2015 04:30:50 AM 20 December, 2015 4:30:50 20 December, 2015 04:30:50 ======Y ======== December, 2015 ======y ======== December, 2015

DateTime.Parse(string)

Nếu bạn có một chuỗi Date định dạng tiêu chuẩn bạn dễ dàng chuyển nó thành đối tượng DateTime thông qua phương thức tĩnh DateTime.Parse(string). Thông thường các chuỗi ngày tháng thời gian bạn thấy trên Internet là các chuỗi định dạng chuẩn, các cơ sở dữ liệu MySQL hoặc SQL Server cũng sử dụng các định dạng chuẩn để hiển thị ngày tháng thời gian.

string w3Time = “2016/05/26 14:37:11”; string nyTime = “Thursday, February 26, 2012”; string isoTime = “2016-02-10”; string windowsTime = “11/21/2015 11:35 PM”; string windowsPanelTime = “11:07:03 PM”;

string w3Time = “2016/05/26 14:37:11”; string nyTime = “Thursday, February 26, 2012”; string isoTime = “2016-02-10”; string windowsTime = “11/21/2015 11:35 PM”; string windowsPanelTime = “11:07:03 PM”;

Trong phần này tôi sẽ hướng dẫn bạn chuyển một đối tượng DateTime ra một string có định dạng tùy biến, chẳng hạn“dd/MM/yyyy”,…. và ngược lại.

Sử dụng DateTime.ToString(string):

string format = “dd/MM/yyyy HH:mm:ss”; DateTime now = DateTime.Now; string s = now.ToString(format); public static DateTime Parse(string s) public static DateTime Parse(string s, IFormatProvider provider) public static DateTime Parse(string s, IFormatProvider provider, DateTimeStyles styles) public static bool TryParseExact(string s, string format, IFormatProvider provider, DateTimeStyles style, out DateTime result) public static bool TryParseExact(string s, string[] formats, IFormatProvider provider, DateTimeStyles style, out DateTime result) Phương thứcVí dụ

string format = “dd/MM/yyyy HH:mm:ss”; DateTime now = DateTime.Now; string s = now.ToString(format); public static DateTime Parse(string s) public static DateTime Parse(string s, IFormatProvider provider) public static DateTime Parse(string s, IFormatProvider provider, DateTimeStyles styles) public static bool TryParseExact(string s, string format, IFormatProvider provider, DateTimeStyles style, out DateTime result) public static bool TryParseExact(string s, string[] formats, IFormatProvider provider, DateTimeStyles style, out DateTime result) Phương thứcVí dụ

static DateTime Parse(string)

static DateTime ParseExact( string s, string format, IFormatProvider provider )

string dateString = “20160319 09:57”; DateTime.ParseExact(dateString ,”yyyyMMdd HH:mm”,null);

static bool TryParseExact( string s, string format, IFormatProvider provider, DateTimeStyles style, out DateTime result )

Bởi vậy, mình viết bài này là muốn hệ thống lại các sản phẩm của The Ordinary cho các bạn, nhất là các bạn mới tiện theo dõi và lựa chọn sản phẩm thích hợp với nhu cầu của mình. Nếu bạn muốn bắt đầu sử dụng mỹ phẩm một cách có khoa học hơn thì các sản phẩm của The Ordinary sẽ là sự khởi đầu rất thích hợp đấy. Mình tin rằng kiến thức của bạn về các thành phần hóa học thông dụng trong mỹ phẩm sẽ lên kha khá sau khi bạn nắm và hiểu được hệ thống sản phẩm của The Ordinary.

Hướng Dẫn Sử Dụng The Ordinary

Các lưu ý chung cho các sản phẩm của The Ordinary

Tất cả các sản phẩm của The Ordinary đều an toàn và không chứa các thành phần có hại như paraben, sunfat, dầu khoáng, dầu động vật, thủy ngân hay formaldehyde… Tuy nhiên, các sản phẩm này chưa từng test trên cơ thể của phụ nữ mang thai hoặc cho con bú. Chính vì thế lời khuyên dành cho các chị em nếu rơi vào hai trường hợp trên đó là không nên sử dụng một số sản phẩm của The Ordinary như là các viên uống bổ sung (FOUNTAIN, AB CREW…) và đặc biệt là các sản phẩm có chứa retinoids như là Granactive Retinoid hoặc Retinol.

Thời hạn sử dụng các sản phẩm của The Ordinary là từ 6 tới 12 tháng tính từ ngày mở nắp. Bạn có thể tìm thông tin chính xác cho từng sản phẩm trên bao bì sản phẩm cũng như vỏ hộp.

Tổng hợp hệ thống sản phẩm của The Ordinary

7. Các loại dầu và dưỡng ẩm

8. Các sản phẩm có đa dạng phân tử (giúp thẩm thấu tốt hơn vào da)

Để có hiệu quả tốt nhất thì bạn nên sử dụng xen kẽ (dùng loại này một thời gian và loại kia một thời gian) giữa các sản phẩm nằm trong nhóm Peptides (mình sẽ ghi rõ), và các sản phẩm chứa axit và Vitamin C (bao gồm L-Ascorbic Axit và Ethylated Ascorbic Axit)

9. Các sản phẩm chống nắng của The Ordinary

Một số các kết hợp cơ bản từ các sản phẩm của The Ordinary

Vừa rồi mình đã tổng hợp các sản phẩm của The Ordinary vào từng nhóm riêng biệt. Bạn có thể nắm được công dụng chính của từng nhóm sản phẩm bằng cách xem qua một vài sản phẩm trong nhóm.

Tuy nhiên, để kết hợp các sản phẩm sao cho hiệu quả thì có lẽ còn cần phải tìm hiểu sâu hơn chút nữa. Vì vậy, nhằm giúp các bạn định hướng, thì mình nghĩ cách tốt nhất là đưa ra một vài ví dụ về các công thức kết hợp cơ bản cho các sản phẩm của The Ordinary.

Chống lại các dấu hiệu lão hóa:

Buổi ngày: Sử dụng “Buffet”, Hyaluronic Acid 2% + B5

Buổi tối: Sử dụng “Buffet”, Granactive Retinoid 2% or 5% in Squalane, 100% Organic Cold-Pressed Rose Hip Seed Oil

Lưu ý luôn luôn bảo vệ da dưới ánh nắng mặt trời.

Ban ngày: Alpha Arbutin 2% + HA, Niacinamide 10% + Zinc 1%, Magnesium Ascorbyl Phosphate 10%

Buổi tối: Alpha Arbutin 2% + HA, Azelaic Acid Suspension 10%

Lưu ý: Ascorbyl Tetraisopalmitate Solution 20% in Vitamin F có thể sử dụng vào buổi tối trước khi sử dụng Azelaic Acid Suspension 10% để tăng thêm hiệu quả

Luôn luôn bảo vệ da dưới ánh nắng mặt trời

Công thức kết hợp để tăng độ ẩm, giữ nước cho tế bào da

Ban ngày: Hyaluronic Acid 2% + B5, Natural Moisturizing Factors + HA

Buổi tối: Hyaluronic Acid 2% + B5, 100% Plant-Derived Squalane

Lưu ý: Có thể thay thế 100% Plant-Derived Squalane bằng 100% Cold-Pressed Virgin Marula Oil hoặc 100% Organic Cold-Pressed Moroccan Argan Oil vào buổi tối, tùy theo mục đích cụ thể của bạn

Luôn luôn bảo vệ da dưới ánh nắng mặt trời

Sửa chữa các nhược điểm trên da

Ban ngày: Niacinamide 10% + Zinc 1%

Buổi tối: Salicylic Acid 2% Solution, Niacinamide 10% + Zinc 1%

Luôn luôn bảo vệ da dưới ánh nắng mặt trời

Chống lại các bất thường về kết cấu da (mụn, đường nhăn, nếp nhăn, da thô ráp…)

Ban ngày: Azelaic Acid Suspension 10%

Buổi tối: Glycolic Acid 7% Toning Solution, Granactive Retinoid 2% or 5% in Squalane

Luôn luôn bảo vệ da dưới ánh nắng mặt trời

Chúng ta cần 2 class tham gia vào ví dụ này.

HelloMain là một class thông thường có hàm main, nó là một luồng chính (main thread).

HelloThread là một class mở rộng từ class Thread. Nó được tạo và chạy kích hoạt chạy bên trong luồng chính và sẽ chạy song song với luồng chính.

package org.o7planning.tutorial.thread.hellothread; public class HelloMain { public static void main(String[] args) throws InterruptedException { int idx = 1; for (int i = 0; i < 2; i++) { System.out.println(“Main thread running ” + idx++); Thread.sleep(2101); } HelloThread helloThread = new HelloThread(); helloThread.start(); for (int i = 0; i < 3; i++) { System.out.println(“Main thread running ” + idx++); Thread.sleep(2101); } } } package org.o7planning.tutorial.thread.hellothread; public class HelloThread extends Thread { @Override public void run() { int index = 1; for (int i = 0; i < 10; i++) { System.out.println(” – HelloThread running ” + index++); try { Thread.sleep(1030); } catch (InterruptedException e) { } } } }

package org.o7planning.tutorial.thread.hellothread; public class HelloMain { public static void main(String[] args) throws InterruptedException { int idx = 1; for (int i = 0; i < 2; i++) { System.out.println(“Main thread running ” + idx++); Thread.sleep(2101); } HelloThread helloThread = new HelloThread(); helloThread.start(); for (int i = 0; i < 3; i++) { System.out.println(“Main thread running ” + idx++); Thread.sleep(2101); } } } package org.o7planning.tutorial.thread.hellothread; public class HelloThread extends Thread { @Override public void run() { int index = 1; for (int i = 0; i < 10; i++) { System.out.println(” – HelloThread running ” + index++); try { Thread.sleep(1030); } catch (InterruptedException e) { } } } }

Kết quả chạy class HelloMain:

Bạn cũng có thể tạo một thread từ một class thi hành interface Runnable. Xem ví dụ minh họa:

package org.o7planning.tutorial.thread.runnable; public class RunnableDemo implements Runnable { @Override public void run() { int idx = 1; for (int i = 0; i < 5; i++) { System.out.println(“Hello from RunnableDemo ” + idx++); try { Thread.sleep(2000); } catch (InterruptedException e) { } } } } package org.o7planning.tutorial.thread.runnable; public class RunnableTest { public static void main(String[] args) throws InterruptedException { System.out.println(“Main thread running..”); Thread thread = new Thread(new RunnableDemo()); thread.start(); Thread.sleep(5000); System.out.println(“Main thread stopped”); } }

package org.o7planning.tutorial.thread.runnable; public class RunnableDemo implements Runnable { @Override public void run() { int idx = 1; for (int i = 0; i < 5; i++) { System.out.println(“Hello from RunnableDemo ” + idx++); try { Thread.sleep(2000); } catch (InterruptedException e) { } } } } package org.o7planning.tutorial.thread.runnable; public class RunnableTest { public static void main(String[] args) throws InterruptedException { System.out.println(“Main thread running..”); Thread thread = new Thread(new RunnableDemo()); thread.start(); Thread.sleep(5000); System.out.println(“Main thread stopped”); } }

4- Luồng Deamon (Deamon Thread)

Java chia thread làm 2 loại một loại thông thường và Deamon Thread. Chúng chỉ khác nhau ở cách thức ngừng hoạt động. Trong một chương trình các luồng thông thường và luồng Deamon chạy song song với nhau. Khi tất cả các luồng thông thường kết thúc, mọi luồng Deamon cũng sẽ bị kết thúc theo bất kể nó đang làm việc gì.

Sử dụng setDeamon(boolean) để sét đặt một luồng là Deamon hoặc không. Chú ý, bạn chỉ có thể gọi hàm setDeamon(boolean) khi thread chưa được chạy. Điều đó có nghĩa là khi thread đã chạy bạn không thể chuyển luồng từ non-deamon sang deamon và ngược lại.

Khi một luồng mới được tạo ra, nó được thừa hưởng đặc tính deamon từ luồng cha. Như vậy khi bạn tạo một luồng trong hàm main của 1 class nó vốn là luồng non-deamon, vì vậy thread tạo ra mặc định cũng là none-deamon. Như vậy nếu bạn tạo một luồng mới trong một luồng Deamon, mặc định nó cũng sẽ là Deamon.

Thread thread = new MyThread(); thread.setDeamon(true); thread.setDeamon(false);

Thread thread = new MyThread(); thread.setDeamon(true); thread.setDeamon(false);

Để dễ hiểu chúng ta xem ví dụ sau, chúng ta cần 3 class tham gia vào minh họa:

package org.o7planning.tutorial.thread.deamon; public class NoneDeamonThread extends Thread { @Override public void run() { int i = 0; while (i < 10) { System.out.println(” – Hello from None Deamon Thread ” + i++); try { Thread.sleep(1000); } catch (InterruptedException e) { } } } } package org.o7planning.tutorial.thread.deamon; class DeamonThread extends Thread { @Override public void run() { int count = 0; while (true) { System.out.println(“+ Hello from Deamon Thread ” + count++); try { sleep(2000); } catch (InterruptedException e) { } } } } package org.o7planning.tutorial.thread.deamon; public class DaemonTest { public static void main(String[] args) { Thread deamonThread = new DeamonThread(); deamonThread.setDaemon(true); deamonThread.start(); new NoneDeamonThread().start(); try { Thread.sleep(5000); } catch (InterruptedException e) { } } }

package org.o7planning.tutorial.thread.deamon; public class NoneDeamonThread extends Thread { @Override public void run() { int i = 0; while (i < 10) { System.out.println(” – Hello from None Deamon Thread ” + i++); try { Thread.sleep(1000); } catch (InterruptedException e) { } } } } package org.o7planning.tutorial.thread.deamon; class DeamonThread extends Thread { @Override public void run() { int count = 0; while (true) { System.out.println(“+ Hello from Deamon Thread ” + count++); try { sleep(2000); } catch (InterruptedException e) { } } } } package org.o7planning.tutorial.thread.deamon; public class DaemonTest { public static void main(String[] args) { Thread deamonThread = new DeamonThread(); deamonThread.setDaemon(true); deamonThread.start(); new NoneDeamonThread().start(); try { Thread.sleep(5000); } catch (InterruptedException e) { } } }

Kết quả chạy class DeamonTest:

Luồng deamon thường dùng làm gì?

Một trong các luồng Deamon quan trọng của Java đó là luồng gom rác ( Garbage Collection Thread), nghĩa là gom các tài nguyên không còn sử dụng để giải phóng bộ nhớ. Khi tất cả các luồng người dùng không còn hoạt động nữa luồng gom rác cũng bị dừng theo.

Thread.join() là một method thông báo rằng hãy chờ thread này hoàn thành rồi thread cha mới được tiếp tục chạy.

public final void join() throws InterruptedException; public final synchronized void join(long millis) throws InterruptedException; public final synchronized void join(long millis, int nanos) throws InterruptedException;

public final void join() throws InterruptedException; public final synchronized void join(long millis) throws InterruptedException; public final synchronized void join(long millis, int nanos) throws InterruptedException;

Hãy xem một ví dụ minh họa:

package org.o7planning.tutorial.thread.join; public class JoinThread extends Thread { private String threadName; private int count; public JoinThread(String threadName, int count) { this.threadName = threadName; this.count = count; } @Override public void run() { for (int i = 1; i < count + 1; i++) { System.out.println(“Hello from ” + this.threadName + ” ” + i); try { Thread.sleep(2000); } catch (InterruptedException e) { } } } } package org.o7planning.tutorial.thread.join; public class JoinTest { public static void main(String[] args) throws InterruptedException { Thread joinThreadA = new JoinThread(“A*”, 2); Thread joinThreadB = new JoinThread(“B*”, 3); Thread noJoinThreadC = new JoinThread(“C”, 5); joinThreadA.start(); joinThreadB.start(); noJoinThreadC.start(); joinThreadA.join(); joinThreadB.join(); System.out.println(“Hello from main thread…”); System.out.println(“Thread A isLive? ” + joinThreadA.isAlive()); System.out.println(“Thread B isLive? ” + joinThreadB.isAlive()); System.out.println(“Thread C isLive? ” + noJoinThreadC.isAlive()); } }

package org.o7planning.tutorial.thread.join; public class JoinThread extends Thread { private String threadName; private int count; public JoinThread(String threadName, int count) { this.threadName = threadName; this.count = count; } @Override public void run() { for (int i = 1; i < count + 1; i++) { System.out.println(“Hello from ” + this.threadName + ” ” + i); try { Thread.sleep(2000); } catch (InterruptedException e) { } } } } package org.o7planning.tutorial.thread.join; public class JoinTest { public static void main(String[] args) throws InterruptedException { Thread joinThreadA = new JoinThread(“A*”, 2); Thread joinThreadB = new JoinThread(“B*”, 3); Thread noJoinThreadC = new JoinThread(“C”, 5); joinThreadA.start(); joinThreadB.start(); noJoinThreadC.start(); joinThreadA.join(); joinThreadB.join(); System.out.println(“Hello from main thread…”); System.out.println(“Thread A isLive? ” + joinThreadA.isAlive()); System.out.println(“Thread B isLive? ” + joinThreadB.isAlive()); System.out.println(“Thread C isLive? ” + noJoinThreadC.isAlive()); } }

Kết quả chạy class JoinTest:

Ví dụ sử dụng join(long millis):

package org.o7planning.tutorial.thread.join; public class JoinTest2 { public static void main(String[] args) throws InterruptedException { Thread joinThreadA = new JoinThread(“A*”, 5); joinThreadA.start(); joinThreadA.join(5000); System.out.println(“Main thread after 5000 milli second”); System.out.println(“Hello from main thread…”); System.out.println(“Thread A isLive? ” + joinThreadA.isAlive()); } }

package org.o7planning.tutorial.thread.join; public class JoinTest2 { public static void main(String[] args) throws InterruptedException { Thread joinThreadA = new JoinThread(“A*”, 5); joinThreadA.start(); joinThreadA.join(5000); System.out.println(“Main thread after 5000 milli second”); System.out.println(“Hello from main thread…”); System.out.println(“Thread A isLive? ” + joinThreadA.isAlive()); } }

6- Xử lý ngoại lệ cho Thread

Phương thức Thread.setDefaultUncaughtExceptionHandler() thiết lập mặc định xử lý khi luồng đột ngột chấm dứt do một ngoại lệ còn tự do, mà không có xử lý khác đã được xác định cho luồng đó.

package org.o7planning.tutorial.thread.exception; import java.util.Random; public class ThreadExceptionDemo { public static class RunnableTest implements Runnable { @Override public void run() { System.out.println(“Thread running ..”); while (true) { Random r = new Random(); int i = r.nextInt(100); System.out.println(“Next value ” + i); try { Thread.sleep(2000); } catch (InterruptedException e) { } throw new RuntimeException(“Have a problem…”); } } } } public static void main(String[] args) { Thread thread = new Thread(new RunnableTest()); Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { System.out.println(“#Thread: ” + t); System.out.println(“#Thread exception message: ” + e.getMessage()); } }); thread.start(); } }

package org.o7planning.tutorial.thread.exception; import java.util.Random; public class ThreadExceptionDemo { public static class RunnableTest implements Runnable { @Override public void run() { System.out.println(“Thread running ..”); while (true) { Random r = new Random(); int i = r.nextInt(100); System.out.println(“Next value ” + i); try { Thread.sleep(2000); } catch (InterruptedException e) { } throw new RuntimeException(“Have a problem…”); } } } } public static void main(String[] args) { Thread thread = new Thread(new RunnableTest()); Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { System.out.println(“#Thread: ” + t); System.out.println(“#Thread exception message: ” + e.getMessage()); } }); thread.start(); } }

Về mặt lý thuyết, “yield” có nghĩa là để cho đi, từ bỏ, đầu hàng. Một luồng yield nói với máy ảo là nó sẵn sàng để cho các thread khác được sắp xếp ở vị trí của nó. Điều này cho thấy rằng nó không phải làm một cái gì đó quá quan trọng. Lưu ý rằng nó chỉ là một gợi ý, mặc dù, và không đảm bảo có hiệu lực ở tất cả.

yield() được định nghĩa như sau trong Thread.java

public static native void yield();

public static native void yield();

Như vậy phương thức yield() được sử dụng khi bạn bạn thấy rằng thread đó đang rảnh rỗi, nó không phải làm việc gì quan trọng, nên nó gợi ý hệ điều hành tạm thời nhường quyền ưu tiên cho các luồng khác.

package org.o7planning.tutorial.thread.yield; import java.util.Date; public class YieldThreadExample { private static Date importantEndTime; private static Date unImportantEndTime; public static void main(String[] args) { importantEndTime = new Date(); unImportantEndTime = new Date(); System.out.println(“Create thread 1”); Thread importantThread = new ImportantThread(); importantThread.setPriority(Thread.MAX_PRIORITY); System.out.println(“Create thread 2”); Thread unImportantThread = new UnImportantThread(); unImportantThread.setPriority(Thread.MIN_PRIORITY); unImportantThread.start(); importantThread.start(); } static class ImportantThread extends Thread { @Override public void run() { for (int i = 0; i < 100000; i++) { System.out.println(“n Important work ” + i); Thread.yield(); } importantEndTime = new Date(); printTime(); } } static class UnImportantThread extends Thread { @Override public void run() { for (int i = 0; i < 100000; i++) { System.out.println(“n — UnImportant work ” + i); } unImportantEndTime = new Date(); printTime(); } } private static void printTime() { long interval = unImportantEndTime.getTime() – importantEndTime.getTime(); System.out.println(“UnImportant Thread – Important Thread = ” + interval + ” milliseconds”); } }

package org.o7planning.tutorial.thread.yield; import java.util.Date; public class YieldThreadExample { private static Date importantEndTime; private static Date unImportantEndTime; public static void main(String[] args) { importantEndTime = new Date(); unImportantEndTime = new Date(); System.out.println(“Create thread 1”); Thread importantThread = new ImportantThread(); importantThread.setPriority(Thread.MAX_PRIORITY); System.out.println(“Create thread 2”); Thread unImportantThread = new UnImportantThread(); unImportantThread.setPriority(Thread.MIN_PRIORITY); unImportantThread.start(); importantThread.start(); } static class ImportantThread extends Thread { @Override public void run() { for (int i = 0; i < 100000; i++) { System.out.println(“n Important work ” + i); Thread.yield(); } importantEndTime = new Date(); printTime(); } } static class UnImportantThread extends Thread { @Override public void run() { for (int i = 0; i < 100000; i++) { System.out.println(“n — UnImportant work ” + i); } unImportantEndTime = new Date(); printTime(); } } private static void printTime() { long interval = unImportantEndTime.getTime() – importantEndTime.getTime(); System.out.println(“UnImportant Thread – Important Thread = ” + interval + ” milliseconds”); } }

Kết quả: thread có ưu tiên thấp hơn đã hoàn thành công việc trước 51 mili giây so với thread có ưu tiên cao hơn.

8- So sánh sleep() và wait()

Cập nhật thông tin chi tiết về Hướng Dẫn Sử Dụng Biểu Thức Chính Quy Trong Java trên website Channuoithuy.edu.vn. Hy vọng nội dung bài viết sẽ đáp ứng được nhu cầu của bạn, chúng tôi sẽ thường xuyên cập nhật mới nội dung để bạn nhận được thông tin nhanh chóng và chính xác nhất. Chúc bạn một ngày tốt lành!