Javase basic review strategy 9 and javase Introduction 9

Source: Internet
Author: User
Tags time in milliseconds

Javase basic review strategy 9 and javase Introduction 9

This article will summarize the thread mechanism in JAVA. When talking about threads, you will certainly ask what is the difference between threads and processes? I also had such questions when I first came into contact with processes. Today I will give you a brief introduction to processes and threads. A Process is a running activity of a computer program about a closed dataset. It is the basic unit for the system to allocate and schedule resources and the basis of the operating system structure; A thread is the sequential control flow within a program. Their differences:

Each process has an independent code and data space, and switching between processes has a lot of overhead. Threads can be seen as lightweight processes, sharing code blocks and data spaces with processes, each process has an independent running stack and program counter (PC), with a low overhead for inter-thread switching.

JAVA threads are implemented through the java. lang. Thread class. When a VM is started, a Thread defined by the main method (public static void main. You can create a Thread by creating an instance of the Thread. Each Thread performs operations through the method run () corresponding to a specific Thread object. The method run () is called the Thread body. Start the Thread by calling the start () method of the Thread.

1. Thread creation and startup:

Public class Th {/*** @ param thread creation and startup */public static void main (String [] args) {// The first Thread creation method Runnable run = new myRunnable (); Thread th1 = new Thread (run); // The second Thread creation method myThread H2. new myThread (); // The thread starts th1.start (); th2.start (); for (int I = 0; I <50; I ++) {System. out. println ("main thread") ;}} class myRunnable implements Runnable {public void run () {for (int I = 0; I <50; I ++) {System. out. println ("Thread 1") ;}} class myThread extends Thread {public void run () {for (int I = 0; I <50; I ++) {System. out. println ("thread 2 ");}}}

2. Basic thread control:

  

3. sleep, join, and yield:

Sleep (int time): sleep, current thread sleep time in milliseconds

Join (): thread merge

Yield: giving way to the CPU and giving other threads the opportunity to execute

Instance code:

Public class SJY {/*** @ param sleep, join, yield usage */public static void main (String [] args) {Runnable run = new myRun (); thread th1 = new Thread (run); myTh th1 = new myTh (); for (int I = 0; I <50; I ++) {if (I! = 25) {System. out. println ("main thread");} else {th1.yield (); // let out the CPU} th1.start (); th2.start (); try {th1.join (); // thread merge th1.sleep (1000*3); // sleep for 3 seconds} catch (InterruptedException e) {e. printStackTrace () ;}} class myRun implements Runnable {public void run () {for (int I = 0; I <50; I ++) {System. out. println ("Thread 1") ;}} class myTh extends Thread {public void run () {for (int I = 0; I <50; I ++) {System. out. println ("thread 2 ");}}}

4. thread priority:

JAVA provides a thread scheduler to monitor all threads in the ready state after the program is started. The thread scheduler determines the thread to execute according to the thread priority. The priority of a thread is represented by a number ranging from 1 ~ 10. The default priority of a thread is 5. Thread. MIN_PRIORITY = 1; Thread. MAX_PRIORITY = 10; Thread. NORM_PRIORITY = 5.

Use the following method to get the thread priority and set the thread priority: int getPriority (): Get the thread priority, void setPriority (int newPriority): Set the thread priority

5. Thread Synchronization:

What does thread synchronization mean? The lock mechanism is added here. synchronized is the key word for locking in JAVA. For thread synchronization, see the following example:

Public class SYN implements Runnable {/*** @ param mutex lock, thread synchronization */Text text Text = new Text (); public static void main (String [] args) {SYN syn = new SYN (); Thread th1 = new Thread (syn); Thread th1 = new Thread (syn); th1.setName ("th1 "); th2.setName ("Th1"); th1.start (); th2.start ();} public void run () {text. add (Thread. currentThread (). getName () ;}} class Text {private static int num = 0; public synchronized void add (String name) {// synchronized (this) {// lock, ensure that the Thread synchronizes num ++; try {Thread. sleep (1); System. out. println (name + ", you are the" + num + "thread using Text");} catch (InterruptedException e) {e. printStackTrace ();}//}}}

6. deadlock:

Public class Test implements Runnable {/*** @ param deadlock */public static void main (String [] args) {Test t1 = new Test (); test t2 = new Test (); t1.flag = 1; t2.flag = 0; Thread th1 = new Thread (t1); Thread th1 = new Thread (t2); th1.start (); th2.start ();} private int flag = 1; static Object o1 = new Object (); static Object o2 = new Object (); public void run () {System. out. println ("flag =" + flag); if (flag = 1) {synchronized (o1) {try {Thread. sleep (5000);} catch (InterruptedException e) {e. printStackTrace ();} synchronized (o2) {System. out. println ("1") ;}}if (flag = 0) {synchronized (o2) {try {Thread. sleep (5000);} catch (InterruptedException e) {e. printStackTrace ();} synchronized (o1) {System. out. println ("2 ");}}}}}

Here, the JAVA thread summary is complete. Next network programming.

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.