catalogue
Static agency mode: (wedding company)
Lamda expression:
- Understanding the functional interface is the key to learning java 8 lambda expressions
- Definition of functional interface:
- Any interface that contains only one abstract method is a functional interface
- public interface Runnable{ public abstract void run(); }
- For functional interfaces, we can create objects of the interface through lambda expressions
- Any interface that contains only one abstract method is a functional interface
/* * Derivation of lambda expressions * */ public class TestLambda01 { //3. Static internal class static class Like2 implements ILike{ @Override public void lambda() { System.out.println("i like lambda2"); } } public static void main(String[] args) { ILike like = new Like(); like.lambda(); like = new Like2(); like.lambda(); //4. Local internal class class Like3 implements ILike{ @Override public void lambda() { System.out.println("i like lambda3"); } } like = new Like3(); like.lambda(); //5. Anonymous inner class. There is no class name. You must use the interface or parent class like = new ILike() { @Override public void lambda() { System.out.println("i like lambda4"); } }; like.lambda(); //6. Simplify with lambda like=()->{ System.out.println("i like lambda5"); }; like.lambda(); } } //1. Define a functional interface interface ILike{ void lambda(); } //2. Implementation class class Like implements ILike{ @Override public void lambda() { System.out.println("i like lambda"); } }
Why use Lambda expressions
- Avoid defining too many inner classes
- It can make the code look concise
- Removed a pile of meaningless code, leaving only the core logic
The simplified code is as follows:
public class TestLambda02 { public static void main(String[] args) { // ILove love = new Love(); // love.love(2); ILove love = a->System.out.println("i love you-->" + a); love.love(520); } } interface ILove{ void love(int a); } //class Love implements ILove{ // @Override // public void love(int a) { // System.out.println("i love you-->" + a); // } //}
Static agency mode: (wedding company)
- Both real objects and proxy objects should implement the same interface
- The proxy object should represent the real role
- Proxy objects can do many things that real objects cannot do
- Real objects can focus on doing their own things
public class StaticProxy { public static void main(String[] args) { You you = new You();//Are you getting married WeddingCompany weddingCompany = new WeddingCompany(you);//To the wedding company weddingCompany.HappyMarry();//Wedding Company Acting Executive } } interface Marry{ void HappyMarry(); } //Real character, I'm married class You implements Marry{ @Override public void HappyMarry() { System.out.println("I'm getting married, Super happy! "); } } //Acting role to help me get married class WeddingCompany implements Marry{ //Agent who -- > real target role private Marry taget; public WeddingCompany(Marry taget){ this.taget = taget; } @Override public void HappyMarry() { before(); this.taget.HappyMarry();//Real object after(); } private void after() { System.out.println("Pick up the garbage after marriage"); } private void before() { System.out.println("Decorate the venue before marriage"); } }
Understand the relationship between Runnable and Thread
new Thread( ()-> System. out. Println ("I love you") start(); new WeddingCompany(new You()).HappyMarry();
By observing the above two expressions, we can see that Thread inherits the Runnable interface and uses the start method for the specified object
Thread status:
Stop thread:
- It is not recommended to use the stop(), destroy() method provided by JDK [obsolete]
- It is recommended that the thread stop by itself
- It is recommended to use a flag bit to terminate the variable. When flag=false, the thread will be terminated
//Test stop // 1. It is recommended that the thread stop normally -- > utilization times, and dead loop is not recommended // 2. It is recommended to use flag bit -- > to set a flag bit // 3. Do not use outdated methods such as stop or destroy, or methods not recommended by JDK public class TestStop implements Runnable { // 1. Set an identification bit private boolean flag = true; @Override public void run() { int i = 0; while (flag){ System.out.println("Thread is running" + i++); } } // 2. Set a public method to stop the thread and convert the flag bit public void stop(){ this.flag = false; } public static void main(String[] args) { TestStop testStop = new TestStop(); new Thread(testStop).start(); for (int i=0;i<1000;i++){ System.out.println("main"+i); if (i==900){ //Call the stop method to switch the flag bit and stop the thread testStop.stop(); System.out.println("It's time for the thread to stop"); } } } }
result:(The main thread runs to 900,End of process,The main thread continues to run) main0 main1 main2 main3 main4 main5 main6 main7 main8 main9 main10 main11 main12 main13 main14 main15 main16 main17 main18 main19 main20 Thread running 0 main21 Thread running 1 Thread running 2 main22 main23 main24 main25 main26 main27 main28 main29 main30 main31 main32 main33 main34 main35 main36 main37 main38 main39 main40 main41 main42 main43 main44 main45 main46 main47 main48 main49 main50 main51 main52 main53 main54 Thread running 3 Thread running 4 main55 Thread running 5 Thread running 6 main56 main57 main58 main59 main60 main61 main62 main63 main64 Thread running 7 main65 main66 main67 main68 main69 main70 main71 main72 main73 main74 main75 main76 main77 main78 main79 main80 main81 main82 main83 main84 main85 main86 main87 main88 main89 main90 main91 main92 main93 main94 main95 main96 main97 main98 main99 main100 Thread running 8 main101 Thread running 9 main102 main103 main104 main105 main106 main107 main108 main109 Thread running 10 Thread running 11 main110 Thread running 12 main111 Thread running 13 main112 Thread running 14 main113 Thread running 15 main114 Thread running 16 main115 Thread running 17 main116 Thread running 18 main117 Thread running 19 main118 main119 main120 main121 main122 main123 main124 main125 main126 main127 main128 main129 main130 main131 main132 main133 main134 main135 main136 main137 main138 main139 main140 main141 main142 main143 main144 main145 main146 main147 main148 main149 main150 main151 main152 main153 main154 main155 main156 main157 main158 main159 main160 main161 main162 main163 main164 main165 main166 main167 main168 main169 main170 main171 Thread running 20 main172 main173 Thread running 21 main174 Thread running 22 main175 Thread running 23 main176 Thread running 24 main177 Thread 25 is running main178 Thread running 26 main179 Thread running 27 main180 Thread running 28 main181 Thread running 29 main182 Thread running 30 main183 Thread running 31 main184 Thread running 32 main185 Thread running 33 main186 Thread running 34 main187 main188 main189 Thread running 35 Thread running 36 Thread running 37 Thread running 38 Thread running 39 Thread running 40 Thread running 41 main190 Thread running 42 Thread running 43 Thread running 44 Thread running 45 Thread running 46 Thread running 47 Thread running 48 Thread running 49 Thread running 50 Thread running 51 Thread running 52 Thread running 53 Thread running 54 Thread running 55 main191 main192 Thread running 56 main193 Thread running 57 Thread running 58 main194 Thread running 59 main195 Thread running 60 main196 Thread running 61 main197 Thread running 62 main198 Thread running 63 main199 Thread running 64 main200 Thread running 65 main201 main202 main203 main204 main205 main206 main207 main208 main209 main210 main211 main212 main213 main214 main215 Thread running 66 main216 Thread running 67 Thread running 68 main217 Thread running 69 main218 Thread running 70 main219 Thread running 71 Thread running 72 main220 main221 Thread running 73 main222 main223 Thread running 74 main224 Thread running 75 main225 Thread running 76 main226 main227 Thread running 77 Thread running 78 Thread running 79 Thread running 80 main228 main229 main230 main231 main232 main233 main234 main235 main236 main237 main238 main239 main240 main241 main242 main243 main244 main245 main246 main247 main248 main249 main250 main251 main252 main253 main254 main255 main256 main257 main258 main259 main260 Thread running 81 main261 main262 main263 main264 main265 main266 main267 main268 main269 main270 main271 main272 main273 main274 Thread running 82 main275 main276 main277 main278 main279 Thread running 83 main280 main281 main282 main283 main284 main285 main286 main287 main288 main289 main290 Thread running 84 main291 Thread running 85 main292 Thread running 86 main293 Thread running 87 main294 Thread running 88 main295 main296 main297 Thread running 89 main298 Thread running 90 main299 main300 main301 main302 main303 main304 main305 main306 main307 main308 main309 main310 main311 main312 main313 main314 main315 main316 main317 main318 main319 main320 main321 main322 main323 main324 main325 main326 main327 main328 main329 main330 main331 main332 main333 main334 main335 main336 main337 main338 main339 main340 main341 main342 main343 main344 main345 main346 main347 main348 main349 main350 main351 main352 main353 main354 main355 main356 main357 main358 main359 main360 main361 main362 main363 main364 main365 main366 main367 main368 main369 main370 Thread running 91 main371 Thread running 92 main372 main373 main374 main375 main376 main377 main378 main379 main380 main381 main382 main383 main384 main385 main386 main387 main388 main389 main390 main391 main392 main393 main394 main395 main396 Thread 93 is running main397 main398 main399 main400 main401 main402 main403 main404 main405 main406 main407 Thread running 94 main408 Thread running 95 main409 Thread running 96 main410 Thread running 97 main411 Thread running 98 main412 main413 main414 main415 main416 Thread running 99 main417 Thread running 100 main418 Thread running 101 main419 Thread running 102 main420 main421 main422 main423 main424 main425 Thread running 103 Thread running 104 Thread running 105 Thread running 106 Thread running 107 Thread running 108 Thread running 109 Thread running 110 Thread running 111 main426 Thread running 112 main427 Thread running 113 main428 Thread running 114 main429 Thread running 115 main430 Thread running 116 main431 Thread running 117 main432 Thread running 118 main433 Thread running 119 Thread running 120 Thread running 121 Thread running 122 main434 Thread running 123 Thread running 124 Thread running 125 Thread running 126 Thread running 127 Thread running 128 Thread running 129 Thread running 130 Thread running 131 Thread running 132 Thread running 133 Thread running 134 Thread running 135 main435 Thread running 136 main436 Thread running 137 main437 Thread running 138 main438 Thread running 139 main439 Thread running 140 main440 Thread running 141 main441 Thread running 142 main442 main443 main444 main445 Thread running 143 main446 Thread running 144 main447 Thread running 145 main448 Thread running 146 main449 Thread running 147 main450 Thread running 148 Thread running 149 Thread running 150 Thread running 151 Thread running 152 Thread running 153 Thread running 154 Thread running 155 Thread running 156 Thread running 157 Thread running 158 Thread running 159 Thread running 160 Thread running 161 Thread running 162 Thread running 163 Thread running 164 Thread running 165 Thread running 166 Thread running 167 Thread running 168 Thread running 169 Thread running 170 Thread running 171 Thread running 172 Thread running 173 Thread running 174 Thread running 175 Thread running 176 Thread running 177 Thread running 178 Thread running 179 Thread running 180 Thread running 181 Thread running 182 Thread running 183 Thread running 184 Thread running 185 Thread running 186 Thread running 187 Thread running 188 Thread running 189 Thread running 190 Thread running 191 Thread running 192 Thread running 193 Thread running 194 Thread running 195 Thread running 196 Thread running 197 Thread running 198 Thread running 199 Thread running 200 Thread running 201 Thread running 202 Thread running 203 Thread running 204 Thread running 205 Thread running 206 Thread running 207 Thread running 208 Thread running 209 Thread running 210 Thread running 211 Thread running 212 Thread running 213 Thread running 214 Thread running 215 Thread running 216 Thread running 217 Thread running 218 Thread running 219 Thread running 220 Thread running 221 Thread running 222 Thread running 223 Thread running 224 Thread running 225 Thread running 226 Thread running 227 Thread running 228 Thread running 229 Thread running 230 Thread running 231 Thread running 232 Thread running 233 Thread running 234 Thread running 235 Thread running 236 Thread running 237 Thread running 238 Thread running 239 Thread running 240 Thread running 241 Thread running 242 Thread running 243 Thread running 244 Thread running 245 Thread running 246 Thread running 247 Thread running 248 Thread running 249 Thread running 250 Thread running 251 Thread running 252 Thread running 253 Thread running 254 Thread running 255 Thread running 256 Thread running 257 Thread running 258 Thread running 259 Thread running 260 Thread running 261 Thread running 262 Thread running 263 Thread running 264 Thread running 265 Thread running 266 Thread running 267 Thread running 268 Thread running 269 Thread 270 running Thread running 271 Thread running 272 Thread running 273 Thread running 274 Thread running 275 Thread running 276 Thread running 277 Thread running 278 Thread running 279 Thread running 280 Thread running 281 Thread running 282 Thread running 283 Thread running 284 Thread running 285 Thread running 286 Thread running 287 Thread running 288 Thread running 289 Thread running 290 Thread running 291 Thread running 292 Thread running 293 Thread running 294 Thread running 295 Thread running 296 Thread running 297 Thread running 298 Thread running 299 Thread running 300 Thread running 301 Thread running 302 Thread running 303 Thread running 304 Thread running 305 Thread running 306 Thread running 307 Thread running 308 Thread running 309 Thread running 310 Thread running 311 Thread running 312 Thread running 313 Thread running 314 Thread running 315 Thread is running 316 Thread running 317 Thread running 318 Thread running 319 main451 Thread running 320 Thread running 321 Thread running 322 Thread is running 323 Thread running 324 Thread running 325 Thread running 326 Thread running 327 Thread is running 328 Thread is running 329 Thread running 330 Thread running 331 Thread running 332 Thread running 333 Thread running 334 Thread running 335 Thread running 336 Thread running 337 main452 Thread running 338 Thread running 339 Thread running 340 Thread running 341 Thread 342 is running Thread running 343 Thread running 344 Thread running 345 Thread running 346 Thread running 347 Thread running 348 Thread running 349 Thread running 350 Thread running 351 main453 Thread running 352 Thread running 353 Thread running 354 Thread running 355 Thread running 356 Thread running 357 Thread running 358 Thread running 359 Thread running 360 Thread running 361 Thread running 362 Thread running 363 Thread running 364 Thread running 365 Thread running 366 Thread running 367 Thread running 368 Thread running 369 Thread running 370 Thread running 371 Thread running 372 Thread running 373 Thread running 374 Thread running 375 Thread running 376 Thread running 377 Thread running 378 Thread running 379 Thread running 380 Thread running 381 Thread running 382 Thread running 383 Thread running 384 Thread running 385 Thread running 386 main454 main455 main456 main457 main458 main459 main460 main461 main462 main463 main464 main465 main466 main467 main468 main469 main470 main471 main472 main473 main474 main475 main476 main477 main478 main479 main480 Thread running 387 main481 main482 main483 main484 main485 main486 main487 main488 main489 main490 main491 main492 main493 Thread running 388 main494 Thread running 389 main495 Thread is running 390 main496 Thread running 391 Thread running 392 Thread running 393 Thread running 394 Thread running 395 Thread running 396 main497 Thread running 397 main498 Thread running 398 main499 main500 Thread running 399 Thread running 400 main501 main502 main503 main504 main505 main506 main507 main508 main509 main510 main511 main512 main513 main514 main515 main516 main517 main518 main519 main520 main521 main522 main523 main524 main525 main526 main527 main528 main529 main530 main531 main532 main533 main534 main535 main536 main537 main538 main539 main540 Thread running 401 Thread running 402 Thread running 403 Thread running 404 main541 Thread running 405 Thread running 406 Thread running 407 Thread running 408 Thread running 409 Thread running 410 Thread running 411 Thread running 412 Thread running 413 Thread running 414 Thread running 415 Thread running 416 Thread running 417 Thread running 418 Thread running 419 Thread running 420 Thread running 421 Thread running 422 Thread running 423 Thread running 424 Thread running 425 Thread running 426 Thread running 427 Thread is running 428 Thread running 429 Thread running 430 Thread running 431 Thread running 432 Thread running 433 Thread running 434 Thread running 435 Thread running 436 main542 main543 main544 main545 Thread running 437 Thread running 438 Thread running 439 main546 Thread running 440 Thread running 441 Thread running 442 Thread running 443 Thread running 444 Thread running 445 Thread running 446 Thread running 447 Thread running 448 Thread running 449 Thread running 450 Thread running 451 Thread running 452 Thread running 453 Thread running 454 Thread running 455 Thread running 456 Thread running 457 Thread running 458 main547 main548 main549 main550 main551 main552 main553 main554 Thread running 459 main555 main556 main557 main558 main559 main560 main561 main562 main563 main564 Thread running 460 main565 main566 Thread running 461 Thread running 462 main567 Thread running 463 main568 Thread running 464 Thread running 465 Thread running 466 Thread running 467 Thread running 468 Thread running 469 Thread running 470 Thread running 471 Thread running 472 Thread running 473 Thread running 474 Thread 475 is running Thread running 476 Thread running 477 Thread running 478 Thread running 479 Thread running 480 Thread running 481 Thread running 482 Thread running 483 Thread running 484 main569 main570 main571 main572 main573 main574 main575 main576 main577 main578 main579 main580 main581 main582 main583 main584 main585 main586 main587 main588 main589 main590 main591 main592 main593 main594 main595 main596 main597 main598 main599 main600 main601 main602 main603 main604 main605 main606 main607 main608 main609 main610 main611 main612 main613 main614 main615 main616 main617 main618 main619 main620 main621 main622 main623 main624 main625 main626 main627 main628 main629 main630 main631 main632 main633 main634 main635 main636 main637 main638 main639 main640 main641 main642 main643 main644 main645 main646 main647 main648 main649 main650 main651 main652 main653 Thread running 485 main654 main655 main656 main657 main658 main659 main660 main661 main662 main663 Thread running 486 main664 main665 main666 main667 main668 main669 main670 main671 main672 main673 main674 main675 main676 main677 main678 main679 main680 Thread running 487 Thread running 488 Thread running 489 Thread running 490 Thread running 491 Thread running 492 Thread running 493 Thread running 494 Thread running 495 Thread running 496 Thread running 497 Thread running 498 Thread running 499 Thread running 500 Thread running 501 Thread running 502 Thread running 503 Thread running 504 Thread running 505 Thread running 506 Thread running 507 Thread running 508 Thread 509 is running Thread running 510 Thread running 511 Thread is running 512 main681 Thread running 513 main682 Thread running 514 Thread running 515 Thread running 516 Thread running 517 Thread running 518 Thread running 519 Thread running 520 Thread running 521 Thread running 522 Thread running 523 Thread running 524 Thread running 525 Thread running 526 Thread running 527 Thread running 528 Thread running 529 Thread running 530 Thread running 531 Thread running 532 Thread running 533 Thread running 534 Thread running 535 Thread running 536 Thread running 537 Thread running 538 Thread running 539 Thread running 540 Thread running 541 Thread running 542 Thread running 543 Thread running 544 Thread running 545 main683 main684 main685 main686 main687 main688 main689 main690 main691 main692 main693 main694 main695 main696 main697 main698 main699 main700 main701 main702 main703 main704 main705 main706 main707 main708 main709 main710 main711 main712 main713 main714 main715 main716 main717 main718 main719 main720 main721 main722 main723 main724 main725 main726 main727 main728 main729 main730 main731 main732 main733 main734 main735 main736 main737 main738 main739 main740 main741 main742 main743 main744 main745 main746 main747 main748 main749 main750 main751 main752 main753 main754 Thread running 546 main755 main756 main757 main758 main759 main760 main761 Thread running 547 Thread running 548 Thread running 549 Thread running 550 Thread running 551 Thread running 552 Thread running 553 Thread running 554 Thread running 555 Thread running 556 Thread running 557 Thread running 558 Thread running 559 Thread running 560 Thread running 561 Thread running 562 Thread running 563 main762 Thread running 564 Thread running 565 Thread running 566 Thread running 567 Thread running 568 Thread running 569 Thread running 570 Thread running 571 Thread running 572 Thread running 573 Thread running 574 Thread running 575 Thread running 576 Thread running 577 Thread running 578 Thread running 579 Thread running 580 main763 main764 main765 main766 main767 main768 main769 main770 main771 main772 main773 main774 main775 main776 main777 main778 main779 main780 main781 main782 main783 main784 main785 main786 main787 main788 main789 main790 main791 Thread running 581 Thread running 582 Thread running 583 Thread running 584 Thread running 585 Thread running 586 Thread running 587 Thread running 588 Thread running 589 Thread running 590 Thread running 591 Thread running 592 Thread running 593 Thread running 594 Thread running 595 Thread running 596 Thread running 597 Thread running 598 main792 main793 main794 main795 main796 main797 main798 main799 main800 main801 main802 main803 main804 main805 main806 main807 main808 main809 Thread running 599 Thread running 600 Thread running 601 Thread running 602 Thread running 603 Thread running 604 Thread running 605 Thread running 606 Thread running 607 Thread running 608 Thread running 609 Thread running 610 Thread running 611 Thread running 612 Thread running 613 Thread running 614 Thread running 615 main810 Thread running 616 Thread running 617 Thread running 618 Thread running 619 Thread running 620 Thread running 621 Thread running 622 Thread running 623 Thread running 624 Thread running 625 Thread running 626 Thread running 627 Thread running 628 Thread running 629 Thread is running Thread running 631 Thread running 632 Thread running 633 main811 main812 main813 main814 main815 main816 main817 main818 main819 main820 main821 main822 main823 main824 main825 main826 main827 main828 main829 main830 main831 main832 main833 main834 main835 main836 main837 main838 main839 main840 main841 main842 main843 main844 main845 main846 main847 main848 main849 main850 main851 main852 main853 main854 main855 main856 main857 main858 main859 main860 main861 main862 main863 main864 Thread running 634 Thread running 635 Thread running 636 Thread running 637 Thread running 638 Thread running 639 Thread is running 640 Thread is running 641 Thread is running 642 Thread is running 643 Thread is running 644 Thread is running 645 Thread is running 646 Thread is running 647 Thread is running 648 Thread is running 649 Thread running 650 Thread running 651 main865 main866 main867 main868 main869 main870 main871 main872 main873 main874 Thread running 652 Thread 653 is running Thread running 654 Thread running 655 Thread running 656 Thread running 657 Thread running 658 main875 main876 main877 main878 main879 main880 main881 main882 Thread running 659 Thread running 660 Thread running 661 Thread running 662 Thread running 663 Thread running 664 Thread running 665 Thread running 666 Thread running 667 Thread running 668 Thread running 669 Thread running 670 Thread running 671 Thread running 672 Thread running 673 Thread running 674 Thread running 675 Thread running 676 Thread running 677 Thread running 678 Thread running 679 Thread running 680 Thread running 681 Thread running 682 Thread running 683 Thread running 684 Thread running 685 Thread running 686 main883 main884 main885 main886 main887 main888 main889 main890 main891 main892 main893 main894 main895 main896 main897 main898 main899 main900 Thread 687 is running It's time for the thread to stop main901 main902 main903 main904 main905 main906 main907 main908 main909 main910 main911 main912 main913 main914 main915 main916 main917 main918 main919 main920 main921 main922 main923 main924 main925 main926 main927 main928 main929 main930 main931 main932 main933 main934 main935 main936 main937 main938 main939 main940 main941 main942 main943 main944 main945 main946 main947 main948 main949 main950 main951 main952 main953 main954 main955 main956 main957 main958 main959 main960 main961 main962 main963 main964 main965 main966 main967 main968 main969 main970 main971 main972 main973 main974 main975 main976 main977 main978 main979 main980 main981 main982 main983 main984 main985 main986 main987 main988 main989 main990 main991 main992 main993 main994 main995 main996 main997 main998 main999 Process finished with exit code 0
Thread sleep:
- Sleep specifies the number of milliseconds the current thread is blocking
- Exception InterruptedException in sleep
- After the sleep time reaches, the thread enters the ready state
- sleep can simulate network delay, countdown, etc
- Every object has a lock, and sleep will not release the lock
Simulate countdown using thread sleep
//Analog countdown public class TestSleep2{ //Countdown 10s public static void tenDown() throws InterruptedException { for (int i = 0; i < 10; i++) { Thread.sleep(1000); System.out.println(10-i); } } public static void main(String[] args) { try { tenDown(); } catch (InterruptedException e) { e.printStackTrace(); } } }
Use thread sleep time to get system time
public class TestSleep2{ public static void main(String[] args) { //Print current system time Date startTime = new Date(System.currentTimeMillis());//get SysTime while (true){ try { Thread.sleep(1000);//Updated every second //Output time System.out.println(new SimpleDateFormat("HH:mm:ss").format(startTime)); startTime = new Date(System.currentTimeMillis());//Update current time } catch (InterruptedException e) { e.printStackTrace(); } } } }
Thread yield:
- Thread comity, which allows the currently executing thread to pause without blocking
- Change the thread from running state to ready state
- Let the cpu reschedule, comity is not necessarily successful! Look at your mood
//Test comity thread //Comity does not necessarily succeed. It depends on your mood public class TestYield { public static void main(String[] args) { MyYield myYield = new MyYield(); new Thread(myYield,"a").start(); new Thread(myYield,"b").start(); } } class MyYield implements Runnable{ @Override public void run() { System.out.println(Thread.currentThread().getName() + "The thread starts executing"); Thread.yield();//Comity System.out.println(Thread.currentThread().getName() + "Thread stop execution"); } }
b thread starts execution
a thread starts execution
b thread stop execution
a thread stops execution
Thread join:
- After the Join merge thread is completed, other threads are executed, and other threads are blocked
- Imagine jumping in line
// Test Join method: imagine jumping in line public class TestJoin implements Runnable { @Override public void run() { for (int i = 0; i<100; i++){ System.out.println("thread vip coming"+i); } } public static void main(String[] args) throws InterruptedException { // Start thread TestJoin testJoin = new TestJoin(); Thread thread = new Thread(testJoin); thread.start(); //Main thread for (int i = 0; i < 100; i++) { if (i == 50){ thread.join();// Jump in line } System.out.println("main" + i); } } }
result : main0 main1 main2 main3 main4 main5 main6 main7 main8 main9 main10 main11 main12 main13 main14 main15 main16 main17 main18 main19 main20 main21 main22 main23 main24 main25 main26 main27 main28 main29 main30 main31 main32 main33 main34 main35 main36 main37 main38 main39 main40 main41 main42 main43 main44 main45 main46 main47 main48 main49 thread vip Here comes 0 thread vip Here comes 1 thread vip Here comes 2 thread vip Here comes 3 thread vip Here comes 4 thread vip Here comes 5 thread vip Here comes 6 thread vip Here comes 7 thread vip Here comes 8 thread vip Here comes 9 thread vip Here comes 10 thread vip Here comes 11 thread vip Here comes 12 thread vip Here comes 13 thread vip Here comes 14 thread vip Here we are 15 thread vip Here comes 16 thread vip Here we are 17 thread vip Here comes 18 thread vip Here comes 19 thread vip Here comes 20 thread vip Here comes 21 thread vip Here comes 22 thread vip Here comes 23 thread vip Here comes 24 thread vip Here comes 25 thread vip Here we are 26 thread vip Here comes 27 thread vip Here comes 28 thread vip Here we are 29 thread vip Here comes 30 thread vip Here we are 31 thread vip Here comes 32 thread vip Coming 33 thread vip Here comes 34 thread vip Here comes 35 thread vip Here we are 36 thread vip Here we are 37 thread vip Coming 38 thread vip Here we are 39 thread vip Here we are 40 thread vip Here we are 41 thread vip Coming 42 thread vip Here we are 43 thread vip Here we are 44 thread vip Here comes 45 thread vip Here we are 46 thread vip Here we are 47 thread vip Here we are 48 thread vip Here we are 49 thread vip Here comes 50 thread vip Here comes 51 thread vip Here we are 52 thread vip Coming 53 thread vip Coming 54 thread vip Coming 55 thread vip Here we are 56 thread vip Here we are 57 thread vip Coming 58 thread vip Here we are 59 thread vip Here comes 60 thread vip Coming 61 thread vip Coming 62 thread vip Coming 63 thread vip Here we are 64 thread vip Here we are 65 thread vip Here we are 66 thread vip Coming 67 thread vip Here we are 68 thread vip Here we are 69 thread vip Here we are 70 thread vip Here we are 71 thread vip Here we are 72 thread vip Here we are 73 thread vip Here we are 74 thread vip Here we are 75 thread vip Here we are 76 thread vip Here we are 77 thread vip Here we are 78 thread vip Here we are 79 thread vip Here comes 80 thread vip Here we are 81 thread vip Coming 82 thread vip Here we are 83 thread vip Coming 84 thread vip Here comes 85 thread vip Coming 86 thread vip Coming 87 thread vip Here we are 88 thread vip Here we are 89 thread vip Here we are 90 thread vip Coming 91 thread vip Here we are 92 thread vip Here we are 93 thread vip Here we are 94 thread vip Here we are 95 thread vip Here we are 96 thread vip Here we are 97 thread vip Here we are 98 thread vip Here we are 99 main50 main51 main52 main53 main54 main55 main56 main57 main58 main59 main60 main61 main62 main63 main64 main65 main66 main67 main68 main69 main70 main71 main72 main73 main74 main75 main76 main77 main78 main79 main80 main81 main82 main83 main84 main85 main86 main87 main88 main89 main90 main91 main92 main93 main94 main95 main96 main97 main98 main99
Thread state observation:
Thread status A thread can be in one of the following states:
- new: threads that have not been started are in this state
- runnable: the thread executing in the Java virtual machine is in this state
- Blocked: the thread that is blocked waiting for the monitor to lock is in this state
- Waiting: the thread that is waiting for another thread to perform a specific action is in this state
- timed_waiting: the thread that has been waiting for another thread's specified action for a long time to reach the specified waiting time is in this state
- terminated: the exited thread is in this state
- The thread after death cannot be started again
A thread can be in a state at a given point in time. These states are virtual machine states that do not reflect the thread state of any operating system
public class TestState { public static void main(String[] args) throws InterruptedException { Thread thread = new Thread(()->{ for (int i = 0; i < 5; i++) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("----------------"); }); //Observation state Thread.State state = thread.getState(); System.out.println(state);//NEW //Observe after startup thread.start();//Start thread state = thread.getState(); System.out.println(state);//Run while (state != Thread.State.TERMINATED){// As long as the thread does not terminate, it will always output the state Thread.sleep(100); state = thread.getState();// Update thread status System.out.println(state);// Output status } } }
result : NEW RUNNABLE TIMED_WAITING TIMED_WAITING TIMED_WAITING TIMED_WAITING TIMED_WAITING TIMED_WAITING TIMED_WAITING TIMED_WAITING TIMED_WAITING TIMED_WAITING TIMED_WAITING TIMED_WAITING TIMED_WAITING TIMED_WAITING TIMED_WAITING TIMED_WAITING TIMED_WAITING TIMED_WAITING TIMED_WAITING TIMED_WAITING TIMED_WAITING TIMED_WAITING TIMED_WAITING TIMED_WAITING TIMED_WAITING TIMED_WAITING TIMED_WAITING TIMED_WAITING TIMED_WAITING TIMED_WAITING TIMED_WAITING TIMED_WAITING TIMED_WAITING TIMED_WAITING TIMED_WAITING TIMED_WAITING TIMED_WAITING TIMED_WAITING TIMED_WAITING TIMED_WAITING TIMED_WAITING TIMED_WAITING TIMED_WAITING TIMED_WAITING TIMED_WAITING TIMED_WAITING TIMED_WAITING TIMED_WAITING TIMED_WAITING TERMINATED
Thread priority:
- Java provides a thread scheduler to monitor all threads that enter the ready state after startup. The thread scheduler determines which thread should be scheduled to execute according to priority
- Thread priority is expressed in numbers, ranging from 1 to 10
- Thread.MIN_PRIORITY = 1;
- Thread.MAX_PRIORITY = 10;
- Thread.NORM_PRIORITY = 5;
- Use the following methods to change or obtain priority
- getPriority().setPriority(int xxx)
// Test thread priority public class TestPriority{ public static void main(String[] args) { //Default priority of main thread System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority()); MyPriority myPriority = new MyPriority(); Thread t1 = new Thread(myPriority); Thread t2 = new Thread(myPriority); Thread t3 = new Thread(myPriority); Thread t4 = new Thread(myPriority); t1.start(); t2.setPriority(1); t2.start(); t3.setPriority(4); t3.start(); t4.setPriority(Thread.MAX_PRIORITY); t4.start(); } } class MyPriority implements Runnable{ @Override public void run() { System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority()); } }
result: main-->5 Thread-3-->10 Thread-0-->5 Thread-2-->4 Thread-1-->1
Summary:
- Priority setting is recommended before start() scheduling
- Low priority only means that the probability of obtaining scheduling is low, not that it will not be called if the priority is low, which depends on the scheduling of cpu
Daemon thread
- Threads are divided into user threads and daemon threads
- The virtual machine must ensure that the user thread has completed execution
- The virtual machine does not have to wait for the daemon thread to finish executing
- For example, record the operation log in the background, monitor the memory, and wait for garbage collection
//Test daemon thread //God protect you public class TestDaemon { public static void main(String[] args) { God god = new God(); You you = new You(); Thread thread = new Thread(god); thread.setDaemon(true);//The default is false, which means user threads. Normal threads are user threads thread.start();//Daemon thread start new Thread(you).start();//User thread start } } //lord class God implements Runnable{ @Override public void run() { while (true){ System.out.println("God bless you"); } } } //you class You implements Runnable{ @Override public void run() { for (int i = 0; i < 36500; i++) { System.out.println("Live happily"); } System.out.println("=====goodbye! world!====="); } }
result:
Normally, the daemon thread will run all the time, but it will follow the main thread and end later
Thread synchronization:
- Concurrency: the same object is operated by multiple threads at the same time
- Because multiple threads of the same process share the same storage space, it brings convenience and access conflict. In order to ensure the correctness of data being accessed in the method, add the lock mechanism synchronized during access. When one thread obtains the exclusive lock of the object and monopolizes resources, other threads must wait and release the lock after use The following problems exist:
- A thread holding a lock will cause all other threads that need the lock to hang;
- In multi-threaded competition, locking and releasing locks will lead to more context switching and scheduling delays, resulting in performance problems
- If a high priority thread waits for a low priority thread to release the lock, it will lead to priority inversion and performance problems
// Unsafe ticket buying // Thread unsafe public class UnsafeBuyTicket { public static void main(String[] args) { BuyTicket station = new BuyTicket(); new Thread(station,"I").start(); new Thread(station,"everybody").start(); new Thread(station, "cattle").start(); } } class BuyTicket implements Runnable{ //ticket private int ticketNums = 10; boolean flag = true;//External stop mode @Override public void run() { //Buy a ticket while (flag){ try { buy(); } catch (InterruptedException e) { e.printStackTrace(); } } } private void buy() throws InterruptedException { //Judge whether there are tickets if (ticketNums<=0){ flag = false; return; } //Analog delay Thread.sleep(100); //Buy a ticket System.out.println(Thread.currentThread().getName() + "Get" +ticketNums--); } }
result:
Everybody gets 10
Scalpers get 9
I got 10
Cattle get 8
I got eight
Everybody got 8
Scalpers get 7
I got six
Everybody gets six
Scalpers get 5
Everybody gets three
I got four
Everybody get 1
Cattle get 2
I got 0
// Unsafe withdrawal // Two people go to the bank to withdraw money, account number public class UnsafeBank { public static void main(String[] args) { // account Account account = new Account(100, "Marriage fund"); Drawing you = new Drawing(account, 50, "you"); Drawing girlFriend = new Drawing(account, 100, "wife"); you.start(); girlFriend.start(); } } //account class Account{ int money; String name; public Account(int money, String name) { this.money = money; this.name = name; } } //Bank, simulated withdrawal class Drawing extends Thread{ Account account;//account // How much did you withdraw int drawingMoney; //How much money do you have now int nowMoney; public Drawing(Account account, int drawingMoney, String name){ super(name); this.account = account; this.drawingMoney = drawingMoney; } @Override public void run() { //Judge whether there is money if (account.money-drawingMoney<0){ System.out.println(Thread.currentThread().getName()+"The money is not enough, Can't take it"); return; } //Thread waiting can amplify the occurrence of the problem try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } //Card balance account.money = account.money-drawingMoney; nowMoney = nowMoney + drawingMoney; System.out.println(account.name + "The balance is" + account.money); //Thread.currentThread().getName() = this,getName: because it inherits the thread method System.out.println(this.getName() + "Money in hand" + nowMoney); } }
Results:
The balance of marriage fund is - 50
The money in your hand is 50
The balance of marriage fund is - 50
The money in his wife's hand is 100
//Thread unsafe collection public class UnsafeList { public static void main(String[] args) { List<String> list = new ArrayList<String>(); for (int i = 0; i < 10000; i++) { new Thread(()->{ list.add(Thread.currentThread().getName()); }).start(); } try { Thread.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(list.size()); } }
result:
9998
Synchronization method:
- Because we can use private keyword to ensure that data objects can only be accessed by methods, we only need to propose a set of mechanism for methods. This mechanism is synchronized keyword, which includes two uses: synchronized method and synchronized block
- Synchronization method: public synchronized void method(int args) {}
- The synchronized method controls the access to "objects". Each object corresponds to a lock. Each synchronized amplification must obtain the lock of the object calling the method before it can be executed, otherwise the thread will block. Once the method is executed, it will monopolize the lock until the method returns, and the lock will not be released until the blocked thread can obtain the lock and continue to execute
- Defect: declaring a large method synchronized will affect efficiency
//synchronized synchronization method private synchronized void buy() throws InterruptedException { //Judge whether there are tickets if (ticketNums<=0){ flag = false; return; } //Analog delay Thread.sleep(100); //Buy a ticket System.out.println(Thread.currentThread().getName() + "Get" +ticketNums--); }
Results:
I got 10
I got 9
Cattle get 8
Scalpers get 7
Cattle get 6
Scalpers get 5
Scalpers get 4
Cattle get 3
Everybody get 2
Everybody get 1
- Synchronization block: synchronized(Obj) {}
- Obj calls it a synchronization monitor
- Obj can say anything, but it is recommended to use shared resources as synchronization monitors
- There is no need to specify a synchronization monitor in the synchronization method, because the synchronization monitor of the synchronization method is this, the object itself, or class
- Synchronization monitor execution process
- The first thread accesses, locks the synchronization monitor, and executes the code in it
- The second thread accesses and finds that the synchronization monitor is locked and cannot be accessed
- After the first thread is accessed, unlock the synchronization monitor
- The second thread accesses, finds that the synchronization monitor has no lock, and then locks and accesses
@Override public void run() { synchronized (account){ //Judge whether there is money if (account.money-drawingMoney<0){ System.out.println(Thread.currentThread().getName()+"The money is not enough, Can't take it"); return; } //Thread waiting can amplify the occurrence of the problem try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } //Card balance account.money = account.money-drawingMoney; nowMoney = nowMoney + drawingMoney; System.out.println(account.name + "The balance is" + account.money); //Thread.currentThread().getName() = this,getName: because it inherits the thread method System.out.println(this.getName() + "Money in hand" + nowMoney); } }
Results:
The balance of marriage fund is 50
The money in your hand is 50
The wife doesn't have enough money to withdraw
Deadlock:
Four necessary conditions for deadlock generation:
- Mutually exclusive condition: a resource can only be used by one process at a time
- Request and hold condition: when a process is blocked by requesting resources, it will hold on to the obtained resources
- Conditions of non deprivation: the resources obtained by the process cannot be forcibly deprived before they are used up
- Circular waiting condition: a circular waiting resource relationship is formed between several processes
The four necessary conditions for deadlock are listed above. We can avoid deadlock as long as we try to break any one or more of them
//Deadlock: multiple threads hold each other's required resources, and then form a deadlock public class DeadLock { public static void main(String[] args) { Makeup g1 = new Makeup(0,"Cinderella"); Makeup g2 = new Makeup(1,"Snow White"); g1.start(); g2.start(); } } //Lipstick class Lipstick{} //mirror class Mirror{} //Make up class Makeup extends Thread{ //Only one resource is needed, which is guaranteed by static static Lipstick lipstick = new Lipstick(); static Mirror mirror = new Mirror(); int choice;//choice String girlName;//People who use cosmetics Makeup(int choice, String girlName){ this.choice = choice; this.girlName = girlName; } @Override public void run() { //Make up try { makeup(); } catch (InterruptedException e) { e.printStackTrace(); } } //Make up, hold each other's locks, and need to get each other's resources private void makeup() throws InterruptedException { if (choice==0){ synchronized (lipstick){//Get lipstick lock System.out.println(this.girlName+"Get lipstick lock"); Thread.sleep(1000); // synchronized (mirror) {/ / want to get the mirror in one second // System.out.println(this.girlName + "get the lock of the mirror"); // } } synchronized (mirror){//I want to get the mirror in a second System.out.println(this.girlName +"Get the lock of the mirror"); } }else { synchronized (mirror){//Get mirror System.out.println(this.girlName+"Get the lock of the mirror"); Thread.sleep(2000); // synchronized (lipstick) {/ / want to get lipstick in one second // System.out.println(this.girlName + "lock to get lipstick"); // } } synchronized (lipstick){//Want to get lipstick in a second System.out.println(this.girlName +"Get lipstick lock"); } } } }