Thread, java thread

Source: Internet
Author: User

Thread, java thread

I. Thread Creation

1. inherit the Thread class to create a Thread class

2. Implement the Runnable interface to create a Thread class

Comparison:

(1) when using the Runnable interface, multiple threads can share the same target object, so it is very suitable for multiple threads to process the same resource.

When you use methods that inherit the Tread class to create a Thread class, multiple threads cannot share the instance variables of the thread class.

(2) The inherited Tread class cannot inherit other parent classes, and the interface class can inherit other parent classes.

We recommend that you use the Runnable interface. ,

 

Ii. Thread Synchronization

Thread security issues. Reason: multiple threads operate on shared data
Solution: encapsulate the thread code for multiple operations to share data. When a thread executes the Code, other threads cannot participate.
You must wait until the current thread finishes executing the code before other threads are allowed to participate in the operation.

Synchronization benefits: Solve thread security issues.
Disadvantages of synchronization: This reduces the efficiency because synchronization locks are determined by all threads outside of synchronization, consuming memory.
Synchronization premise: the synchronization must have multiple threads and use the same lock.

1. synchronous code block

Using synchronous code blocks in Java can solve security problems. Format: synchronized (object)
{Encapsulated code block}

Package com. company;/* thread security issues. Cause: the solution for sharing data among multiple threads is to encapsulate the thread code for sharing data among multiple operations, when a thread executes the Code, other threads cannot participate. It must wait until the current thread finishes executing the code before other threads can come in for calculation. Using synchronous code blocks in Java can solve security problems. Format: synchronized (object) {encapsulated code block} synchronization benefits: Solve thread security issues. Disadvantages of synchronization: This reduces the efficiency because synchronization locks are determined by all threads outside of synchronization, consuming memory. Synchronization premise: the synchronization must have multiple threads and use the same lock. */Class Ticket extends Thread // implements Runnable {Object obj = new Object (); private int num = 100; // If num is set to static, the data is shared. Therefore, these one hundred tickets are sold out by several threads, // if the interface is implemented, the public void run () {while (true) {synchronized (obj) {if (num> 0) will be shared by several threads) {try {// only try catch can be used here. Throw cannot be used, because Runnale, // covered by the run method, and Runnable is not thrown, so the subclass cannot be thrown. Thread. sleep (5); // sleep throws an exception .} catch (InterruptedException e) {} System. out. println (Thread. currentThread (). getName () + ".. sale .. "+ num --) ;}}}} public class TicketDemo {public static void main (String [] args) {Ticket t = new Ticket (); /* Thread t1 = new Thread (t); Thread t2 = new Thread (t); Thread t3 = new Thread (t); t1.start (); t2.start (); t3.start (); */Ticket t1 = new Ticket (); Ticket t2 = new Ticket (); Ticket t3 = new Ticket (); t1.start (); t2.start (); t3.start ();}}

In this Code case, when I change the num value to static data in the inheritance mode, a synchronization error still occurs.

........

Thread-1... sale... 1
Thread-3... sale... 0
Thread-2... sale...-1

Static Locking is required for static variables. Static Locking requires a lock for the entire class object. This object is this class (XXX. class ).

When the thread executes the code block, it gets the lock! When this thread has not been executed, if other threads also execute this code block, it will check whether the Lock of this object is taken away by other threads. If it is removed, this thread will be blocked and wait.

Thread mutex is implemented. Therefore, when no static lock is detected, synchronous security measures cannot be performed on the num static variables. Change the obj lock to Ticket. class.

 

2. Add thread synchronization protection in singleton mode:

// Use the ELE. Me type in multiple practical scenarios/* class Single {private static final Single s = new Single (); private Single () {} public static Single getInstance () {return s ;}} * // lazy multi-interview class Single {private static Single s = null; private Single () {} public static Single getInstance () {if (s = null) // Add one more if judgment to improve efficiency. In fact, if judgment is made in advance, so the lock judgment is missing. {Synchronized (Single. class) // you must use the class name. class. Because it is static. {If (s = null) s = new Single () ;}} return s ;}}

 

3. synchronous Functions

* The lock used by the synchronous function is this
*
* Differences between synchronous functions and synchronous code blocks:
* The lock of the synchronous function is fixed. this
* The lock of the synchronized code block is an arbitrary object.
* We recommend that you use synchronous code blocks.
*
* In this code block, security issues do not occur when the synchronization function and the synchronization code block hold the same lock.
* Holding different locks is indeed equivalent to having no locks, and security issues may occur.
*
* The lock used by the static synchronization function is that the object Class clazz = t. getClass () to which the function belongs; Class clazz = Ticket. class
* You can use the getClass method or the current class name. class.

In the following example, the static synchronous code block lock and the static synchronous function lock are used.

Class Tickets implements Runnable // extends Thread {Object obj = new Object (); private static int num = 200; // when num is set to static, the data is shared. Therefore, the one hundred tickets are sold out by several threads. boolean flag = true; public void run () {if (flag) {while (true) {// synchronized (obj) // {show (); // }}else {while (true) {synchronized (this. getClass () // Ticket. class {if (num> 0) {try {Thread. sleep (20);} catch (InterruptedException e) {} System. out. println (Thread. currentThread (). getName () + ".. obj .. "+ num --) ;}}}} public static synchronized void show () // when using a static function, this cannot reference {if (num> 0) {try {Thread. sleep (20);} catch (InterruptedException e) {} System. out. println (Thread. currentThread (). getName () + ".. static .. "+ num --) ;}} public class SynFunctionLock {public static void main (String [] args) {Tickets t = new Tickets (); // Ticket tt = new Ticket (); // when two instance objects are created, the instance values of two num are sold out. thread t1 = new Thread (t); Thread t2 = new Thread (t); t1.start (); try {Thread. sleep (20);} catch (InterruptedException e) {} t. flag = false; t2.start ();}}View Code

 

4. deadlock

Deadlock: synchronization Nesting is one of the common scenarios.

When two threads hold each other's synchronization locks, a deadlock will occur, and the program will not give an exception. All threads are in a blocking state and cannot continue.

class Test implements Runnable{    private boolean flag;    Test(boolean flag)    {        this.flag=flag;    }    public void run()    {         if(flag)         {                synchronized (MyLock.lockb)                {                                     System.out.println(Thread.currentThread().getName()+"if locka");                    synchronized (MyLock.locka)                    {                        System.out.println(Thread.currentThread().getName()+"if lockb");                    }                }         }        else         {  synchronized (MyLock.locka)           {                       System.out.println(Thread.currentThread().getName()+"else locka");             synchronized (MyLock.lockb)             {                 System.out.println(Thread.currentThread().getName()+"else locka");             }           }         }    }}class MyLock{    public static final Object locka=new Object();    public static final Object lockb=new Object();}class  DeadLockDemo{    public static void main(String [] args)    {        Test a=new Test(true);        Test b=new Test(false);        Thread t1=new Thread(a);        Thread t2=new Thread(b);        t1.start();        t2.start();    }}

 

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.