Java will learn the inevitable thread (2) _java

Source: Internet
Author: User

First, the priority level of the thread

  

Examples of thread priority usage:

Package cn.galc.test;

public class TestThread6 {public
 static void Main (String args[]) {
 MyThread4 t4 = new MyThread4 ();
 MYTHREAD5 T5 = new MyThread5 ();
 thread T1 = new thread (T4);
 Thread t2 = new Thread (T5);
 T1.setpriority (thread.norm_priority + 3);//Use the SetPriority () method to set the priority level of the thread, set the priority level of the T1 thread
  /* To prioritize the thread T1 ( Priority) The normal priority (norm_priority) on the basis of a further increase of level 3 
  * so that the T1 time will be more than T2 a lot more
  * By default, the Norm_priority value is
  5
 * * T1.start ();
 T2.start ();
 SYSTEM.OUT.PRINTLN ("T1 thread priority is:" + t1.getpriority ());
 Use the GetPriority () method to get the priority level of the thread, print out the T1 priority of 8
 }

class MyThread4 implements Runnable {public
 void Run () {for
 (int i = 0; I <= 1000 i++) {
  System.out.println ("T1:" + i);

}}} Class MyThread5 implements Runnable {public
 void run () {for
 (int i = 0; I <= 1000; i++) {
  SYSTEM.OUT.P  Rintln ("===============t2:" + i);
 }
}} As soon as the run () method ends, the thread ends.

Second, thread synchronization

  

Examples of the use of synchronized keywords:

Package cn.galc.test;

public class Testsync implements Runnable {
 Timer timer = new timer ();

 public static void Main (String args[]) {
 Testsync test = new Testsync ();
 thread T1 = new thread (test);
 Thread t2 = new Thread (test);
 T1.setname ("T1");/set the name of the T1 thread
 t2.setname ("T2");//Set the T2 thread's name
 T1.start ();
 T2.start ();
 }

 public void Run () {
 timer.add (Thread.CurrentThread (). GetName ());
 }

Class Timer {
 private static int num = 0;

 public/* synchronized */void Add (String name) {//When declaring a method adding synchronized indicates that the current object is locked during execution of this method
 synchronized (this) {
  /* * Use synchronized (this) to lock the current object, so that no more than two different threads will be able to access the same object resource at the same time. The next thread will be accessed only when one of the threads has finished accessing it.
  num++;
  try {
  thread.sleep (1);
  } catch (Interruptedexception e) {
  e.printstacktrace ();
  }
  SYSTEM.OUT.PRINTLN (name + ": You are the first" + num + "A thread using Timer");}}


Thread deadlock problem:
,

Package cn.galc.test;
 /* This applet simulates the problem of thread deadlock * * * public class Testdeadlock implements Runnable {public int flag = 1;

 static Object O1 = new Object (), O2 = new Object ();
 public void Run () {System.out.println (Thread.CurrentThread (). GetName () + "flag=" + flag); * * Run the program after the implementation of the program to print out here after the flag will no longer execute the following if statement * program also died here, neither down to execute nor exit * * * This is flag=1 this thread * */if (flag = 1) {SYN
  Chronized (O1) {/* uses the SYNCHRONIZED keyword to lock object 01/try {Thread.Sleep (500);
  catch (Interruptedexception e) {e.printstacktrace (); 
   } synchronized (O2) {* * * has locked the object O1, so long as the O2 can be locked, you can print out 1 of the operation * but there is no way to lock the object O2, because in another flag=0 this thread has the object O1 locked
  * Although the thread that locks O2 This object will sleep every 500 milliseconds, but in the sleep is still locked O2 not put the * * SYSTEM.OUT.PRINTLN ("1"); The two if statements here will not be able to execute because a thread deadlock has been created * flag=1 this thread is waiting for the flag=0 thread to unlock the object O2, * and flag=0 this thread is waiting flag=1 the thread to O1 the object Lock Unlock * However, these two threads are unwilling to unlock the locked object, so it creates a thread deadlock problem * * * This is flag=0 this thread */if (flag = = 0) {synchronized (O2) {/* * here First Use SYN Chronized Lock Object O2 * *
  try {thread.sleep (500);
  catch (Interruptedexception e) {e.printstacktrace (); The object O2 is already locked in front of synchronized (O1) {/* *. As long as you can lock the O1, you can print out 0 of the operation, but there is no way to lock object O1, because in another flag=1 this thread has the object O1 locked, although the lock O1 this
  The thread of the object will sleep every 500 milliseconds, but it is still locked in the O1 or System.out.println ("0") during sleep;
 }}} public static void Main (String args[]) {Testdeadlock TD1 = new Testdeadlock ();
 Testdeadlock TD2 = new Testdeadlock ();
 Td1.flag = 1;
 Td2.flag = 0;
 thread T1 = new Thread (TD1);
 Thread t2 = new Thread (TD2);
 T1.setname ("Thread TD1");
 T2.setname ("Thread Td2");
 T1.start ();
 T2.start ();

 }
}

Troubleshooting thread deadlocks It's best to lock only one object and not lock two objects at the same time

Producer Consumer issues:

Package cn.galc.test; /* Example name: Producer-Consumer issues * Source file name: Producerconsumer.java * Main points: * 1. Inconsistency of shared data/protection of critical resources * 2. Concept of the Java object Lock * 3. Synchronized keyword/wait () and Notify () method */public class Producerconsumer {public static void main (String args[]) {SYNCSTAC
  K stack = new Syncstack ();
  Runnable p=new Producer (stack);
  Runnable C = new Consumer (stack);
  Thread P1 = new Thread (p);
  
  Thread C1 = new thread (c);
  P1.start ();
 C1.start ();
 The implementation of a class syncstack{//stack that supports multithreaded synchronization operations private int index = 0; 
 Private char []data = new char[6];
 Public synchronized void push (char c) {if (index = = data.length) {try{this.wait ();
 }catch (Interruptedexception e) {}} this.notify ();
 Data[index] = c;
 index++;
  Public synchronized char pop () {if (index ==0) {try{this.wait ();
 }catch (Interruptedexception e) {}} this.notify ();
 index--;
 return Data[index]; 
 } class Producer implements runnable{Syncstack stack;
 Public Producer (Syncstack s) {stack = s; public void Run () {for(int i=0; i<20; i++)
  {Char c = (char) (Math.random () *26+ ' A ');
  Stack.push (c);
  System.out.println ("produced:" +c); 
  try{thread.sleep ((int) (Math.random () *1000)); 
 }catch (Interruptedexception e) {}} class Consumer implements runnable{stack;
 Public Consumer (Syncstack s) {stack = s;
  public void Run () {for (int i=0;i<20;i++) {char c = stack.pop ();
  System.out.println ("Consumption:" +c);
  try{thread.sleep ((int) (Math.random () *1000));
 }catch (Interruptedexception e) {}}}

The above is about all the content of Java thread Introduction, we can combine the first "Java will learn will be the thread (1)" To learn, hope to help everyone.

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.