Java Basic Learning (iv) JAVA8 threads

Source: Internet
Author: User
Tags thread class

Threads and processes: The operating system performs multitasking, each task is a process, the process performs multitasking, each task is a thread, and contains a relationship.

One, multi-threaded creation and startup:

1. Inherit thread: Override the Run () method and call Start () to launch the thread.

public class Threaddemo extends thread{

@Override public void Run () {

Specific methods

}

}

2. Implement the Runnable interface to create the thread class and call Start () to launch the thread.

public class Runnabledemo implements Runnable {

public void Run () {

Specific methods

}

}

The thread class actually implements the Runable interface as well.

Second, thread resource sharing.

Threaddemo class

public class Threaddemo extends thread{

Public Integer count = 10;

Public String lock = "lock";

Public Threaddemo (String name) {

Super (name);

}

@Override

public void Run () {

Synchronized (lock) {

System.out.println (Thread.CurrentThread (). GetName () + is running. Count: "+count--);

}

}

}

Resources are not shared:

public class ThreadTest {

public static void Main (string[] args) {

Resource not shared

for (int i = 1; i <=; i++) {

String name = "T" +i;

New Threaddemo (name). Start ();

}

}

}

Operation Result:

T4 is running. Count:10

T10 is running. Count:10

T6 is running. Count:10

T1 is running. Count:10

T5 is running. Count:10

T2 is running. Count:10

T8 is running. Count:10

T9 is running. Count:10

T3 is running. Count:10

T7 is running. Count:10

Resource sharing:

public class ThreadTest {

public static void Main (string[] args) {

Resource sharing

Threaddemo t = new Threaddemo ("T1");

for (int i = 1; i <=; i++) {

New Thread (t). Start ();

}

}

Operation Result:

Thread-0 is running. Count:10

Thread-2 is running. Count:9

Thread-1 is running. Count:8

Thread-7 is running. Count:7

Thread-6 is running. Count:6

Thread-8 is running. Count:5

Thread-3 is running. Count:4

Thread-4 is running. Count:3

Thread-5 is running. Count:2

Thread-9 is running. Count:1

Third, threading methods

The life cycle of a thread

There are 5 states for new (new), Ready (Runnable), run (Running), blocking (Blocked), and Death (Dead).

3.1 Join () and join (long Millis), the thread waiting for the join IS finished, and the join thread continues execution.

public class ThreadTest {

public static void Main (string[] args) {

try {

Threaddemo thread1 = new Threaddemo ("Thread1");

Threaddemo thread2 = new Threaddemo ("Thread2");

Thread1.start ();

Thread1.join ();

System.out.println ("Main is running.");

Thread2.start ();

} catch (Exception e) {

E.printstacktrace ();

}

}

}

Operation Result:

Main is running.

Thread1 is running.

Thread2 is running.

Remove the comment:

Run results

Thread1 is running.

Main is running.

Thread2 is running.

The Setdaemon (True) method of the thread object is called to set the specified thread as a background thread.

To set a thread as a background thread, you must call it before start ()

3.2 Thread sleep (long Millis)

The sleep () method is more portable than the yield () method, and it is generally not recommended to use the yield () method to control the execution of concurrent threads.

3.3 Changing the priority of a thread

The thread class provides setpriority (int newpriority) and getpriority () to set

and returns the priority of the specified thread. 10 max, 1 min, normal 5.

3.4 Thread Synchronization

1.synchronized (obj) {

}

2.synchronized modifies a method or block of code, but cannot decorate constructors and member variables.

The Java language keyword that, when used to decorate a method or a block of code, guarantees that at most one thread executes the code at the same time.

1. When two concurrent threads access the synchronized (this) synchronization code block in the same object, only one thread can be executed within a single time. The other thread must wait for the current thread to finish executing the block before it can execute the code block.

2. However, when a thread accesses one synchronized (this) of object to synchronize a block of code, another thread can still access the non-synchronized (this) synchronous code block in the object.

3, in particular, when a thread accesses one synchronized (this) of an object to synchronize a block of code, other threads will block access to all other synchronized (this) synchronization blocks in object.

4. The third example also applies to other synchronization code blocks. That is, when a thread accesses a synchronized (this) of object to synchronize a block of code, it obtains the object lock of the objects. As a result, other threads are temporarily blocking access to all of the synchronization code portions of the object.

5, the above rules for other object locks also apply.

Extension: Single-threaded environment should use StringBuilder to ensure good performance, when the need to ouch to ensure multithreading security,

You should use StringBuffer.

Four, synchronous lock (Lock)

Lock is a tool that controls the access of multiple threads to shared resources. Typically, a lock provides exclusive access to a shared resource, with only one

The thread locks the lock object, and the thread should obtain the lock object before it begins accessing the shared resource.

Reentrantlock locks are reentrant, that is, a thread can lock a locked reentrantlock lock again

The Reentrantlock object maintains a counter to track the nested invocation of the Lock () method, and the thread must display a call to unlock () to release the lock after each call to lock (), so the code for a locked package can invoke another method that is protected by the same lock.

public class Threaddemo extends thread{

Public Integer count = 1;

Private final Reentrantlock lock = new Reentrantlock ();

Public Threaddemo (String name) {

Super (name);

}

@Override

public void Run () {

Lock.lock ();

try {

Perform actions

} catch (Exception e) {

E.printstacktrace ();

}finally {

Lock.unlock ();

}

}

}

Subsequent:

Thread pools, deadlocks, producer consumer patterns, and inter-threading communication are no longer introduced.

Because the wait method is on an object, and the Sleep method is on the thread, when using Thread.Sleep, it does not change the state of the object and therefore does not release the lock

Write more code and read more, and do a quiet coder.

Java Basic Learning (iv) JAVA8 threads

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.