Java Threads: Thread-safe classes and callable and future (threads with return values)

Source: Internet
Author: User

First, Thread safety class

When a class is already well synchronized to protect its data, this class is called thread-safe. When a collection is safe, there are two threads operating on the same collection object, and when the first thread queries the collection is not empty, the second thread also executes the same operation as the first thread, perhaps after the first thread queries, and the second one is not empty, but it is obviously not right at this point. Such as:

1  Public classNameList {2     PrivateList NameList = Collections.synchronizedlist (NewLinkedList ()); 3 4      Public voidAdd (String name) {5 Namelist.add (name);6     } 7 8      PublicString Removefirst () {9         if(Namelist.size () > 0) { Ten             return(String) namelist.remove (0);  One}Else {  A             return NULL;  -         }  -     }  the}
1  Public classTest {2      Public Static voidMain (string[] args) {3         FinalNameList NL =Newnamelist ();4Nl.add ("AAA"); 5         classNamedropperextendsthread{6              Public voidrun () {7String name =Nl.removefirst ();8 System.out.println (name);9             } Ten         }  One  AThread T1 =NewNamedropper (); -Thread t2 =NewNamedropper (); - T1.start (); the T2.start (); -     }  -}

Although the collection object private List namelist=collections.synchronizedlist (new LinkedList ()) is synchronous, the program is not thread-safe.

The reason is that the process of one thread action list cannot prevent another thread from doing other operations on the list. The workaround is to do a synchronization on the namelist of the Action collection object. The rewritten code is:

1  Public classNameList {2     PrivateList NameList = Collections.synchronizedlist (NewLinkedList ()); 3 4      Public synchronized voidAdd (String name) {5 Namelist.add (name);6     } 7 8      Public synchronizedString Removefirst () {9         if(Namelist.size () > 0) { Ten             return(String) namelist.remove (0);  One}Else {  A             return NULL;  -         }  -     }  the}

At this point, when one thread accesses one of the methods, other threads wait.

Second, callable and future

A task that implements a return value by implementing the callable interface is similar to a task that the Runnable interface handles without a return value.

After performing the callable task, you can get a future object that calls get on the object to get the object returned by the callable task. Such as:

1  PackageThread;2 3 Importjava.util.concurrent.Callable;4 Importjava.util.concurrent.ExecutionException;5 ImportJava.util.concurrent.ExecutorService;6 Importjava.util.concurrent.Executors;7 Importjava.util.concurrent.Future;8 9  Public classCallabletest {Ten      Public Static voidMain (string[] args)throwsexecutionexception,interruptedexception{ OneExecutorservice Pool=executors.newfixedthreadpool (2); ACallable c1=NewMycallable ("A"); -Callable c2=NewMycallable ("B"); -Future f1=Pool.submit (C1); theFuture f2=pool.submit (C2); -System.out.println (">>>" +f1.get (). toString ()); -System.out.println (">>>" +f2.get (). toString ()); - Pool.shutdown (); +     } - } + classMycallableImplementscallable{ A     PrivateString oid; at mycallable (String oid) { -          This. oid=OID; -     } -      PublicObject Call ()throwsexception{ -         returnoid+ "What the task returns"; -     } in      -}
View Code
1 >>>A task returned content 2 >>>b The content returned by the task

Java Threads: Thread-safe classes and callable and future (threads with return values)

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.