Java Learning Notes (41)-Multi-threaded and thread groups

Source: Internet
Author: User

Thread Group Threadgroup
/* Thread Group Threadgroup * * Conclusion: * If thread priority is set before the thread group priority is set, thread priority is not subject to thread group priority * If thread priority is set after setting thread group priority, thread priority cannot exceed thread group priority * Thread's excellent The first level, the default is the same as the parent thread that started it, but is restricted by all thread groups */ Public  class Test02 {     Public Static voidMain (string[] args) {System.out.println (Thread.CurrentThread (). GetName () +"Thread, owning thread group:"+ Thread.CurrentThread (). Getthreadgroup ());        System.out.println (Thread.CurrentThread ()); Thread.CurrentThread (). SetPriority (8); Thread th=NewThread ("Mythread"); System.out.println (Th.getpriority ());//Define a group of threads TGThreadgroup TG =NewThreadgroup ("wbs14061 Thread Group"); System.out.println ("Parent thread Group for TG thread Group:"+tg.getparent ());//Create line Cheng, belong to TG thread GroupThread th1=NewThread (TG,NewMyThread2 (),"First"); Thread th2=NewThread (TG,NewMyThread2 (),"Second"); Th1.setpriority (8); Tg.setmaxpriority (4); Th2.setpriority (9); Thread th3=NewThread (TG,NewMyThread2 (),"Third"); System.out.println ("Information for the TG thread group:"+TG);        Th1.start ();        Th2.start (); Th3.start ();//tg.stop ();}} class MyThread2 implements Runnable {    intnum =1; @Override Public voidRun () { while(Num <= -) {System.out.println (Thread.CurrentThread (). GetName () +","+ Thread.CurrentThread (). GetPriority () +"****"+ num++); }    }}
Multi-threaded access to shared data
/ * Multi-threaded access shared data * * Multi-threaded operation shared data may be problematic, that is, thread safety issues * Cause: When multiple threads operate to share data, a thread executes only a subset of the statements, and the CPU time slice switches and another thread participates, causing errors in sharing the data  * FIX: Synchronization mechanism synchronized * * Sync premise: * 1. Must have two or more than two threads * 2. Must be multiple threads using the same lock * * Protection range: * 1. Add only the required code to the synchronized block * 2. Do not add all the code in the Run () method to the synchronized block, otherwise the equivalent of single-threaded * * thread synchronization advantages and disadvantages: * Advantages: resolves the thread safety * disadvantage: Because multiple threads need to make lock judgment, consume resources, resulting in reduced efficiency */ Public  class Test03 {     Public Static voidMain (string[] args) {Ticket Ticket =NewTicket (); Thread Th1 =NewThread (Ticket,"Thread 1"); Thread Th2 =NewThread (Ticket,"Thread 2"); Thread Th3 =NewThread (Ticket,"Thread 3");        Th1.start ();        Th2.start ();    Th3.start (); }} class Ticket implements Runnable {    Private intnum = -;//100 tickets Total, share this dataObject obj =NewObject (); @Override Public voidRun () { while(true) {//Critical code block to secure shared dataSynchronized (obj) {if(Num >0) {Try{Thread.Sleep (Ten); }Catch(Interruptedexception e)                    {E.printstacktrace (); } System.out.println (Thread.CurrentThread (). GetName () +"Sold Tickets:"+ num--); }            }        }    }}
Synchronized method
/* * Using synchronized Modify method, called synchronous method (Synchronous function), thread-safe * * Synchronization function uses the lock is the current object, that is the this lock * static synchronization function used by the lock is a bytecode file object * / Public classTest04 { Public Static void Main(string[] args) {Account account=NewAccount (); Thread th1=NewThread (Account,"Your dad."); Thread th2=NewThread (Account,"Your mother.");        Th1.start ();    Th2.start (); }}/ * * Bank Account class * *Class Bank {Private DoubleBalance//Balance    //view balance     Public void getbalance() {System. out. println ("Current balance:"+ balance); }//Save money     Public void setbalance(DoubleMoney) {balance = balance + money; }}/ * * Two people at the same time to the account of the money, 300 yuan per dozen, a total of 3 times, total 900 yuan * *Class Account implements Runnable {Private StaticBank Bank =NewBank ();Static inti =1; @Override Public void Run() { while(true) {Savemoney (); }    }//Sync function, only one thread can execute this function at a time     Public StaticSynchronizedvoid Savemoney(){if(I <=3) {Try{Thread.Sleep (Ten);//Hibernate 10ms, the number of money will be abnormal}Catch(Interruptedexception e)            {E.printstacktrace (); } bank.setbalance ( -); System. out. println (Thread.CurrentThread (). GetName () +"Saved 300 yuan, the first"+ (i++) +"Times"); Bank.getbalance ();//Print current balance}Else{System.exit (0); }    }}

Java Learning Notes (41)-Multi-threaded and thread groups

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.