Threads are embedded in Java and are not easy to understand. There are books dedicated to Java threads for your reference. This shows the importance of Java threads. This article will introduce the basic knowledge of threads in detail.
Sometimes you may want to write a program to execute related tasks at intervals. At this time, you can use timer and timertask, which is very convenient. For more information, see http://blog.csdn.net/mingjava/archive/2004/07/04/33749.aspx.
There are two ways to implement a thread in Java. The first is to implement the runnable interface to implement its run () method, and the second is to inherit the Thread class and overwrite its run () method. The following is a sample code:
Public class dosomething implements runnable {
Public void run (){
// Here is where you do something
}
}
Public class doanotherthing extends thread {
Public void run (){
// Here is where you do something
}
}
The difference between the two methods is that if your class has inherited other classes, you can only implement the runnable interface, Because Java only allows single inheritance.
Java threads have four states: running, ready, suspended, and ended. If a thread ends, it means it is a dead thread. When you call the START () method of a thread instance, the thread enters the ready state. Note that it is not in the running state, when the virtual machine starts to allocate the running time slice to its CPU, the thread starts to enter the running state. When the thread enters the waiting state, such as waiting for an event, the thread is suspended.
To start a thread, you only need to call the START () method. There are two methods to start the thread for the two methods:
Dosomething doit = new dosomething ();
Thread mythread = new thread (doit );
Mythread. Start ();
Doanotherthing doit = new doanotherthing ();
Doit. Start ();
Because the stop () method in thread is not recommended for security and other factors, if you want to stop a thread, you can set a semaphore, for example:
Public class mythread implements runnable {
Private Boolean quit = false;
Public void run (){
While (! Quit ){
// Do something
}
}
Public void quit (){
Quit = true;
}
}
If each thread only does its own thing, it is easy, but sometimes several threads may need to access an object at the same time and modify it, at this time, you must use the synchronized keyword in the method or code block for thread synchronization. For example:
Public class counter {
Private int counter;
Public synchronized int increment (){
Return ++ counter;
}
Public synchronized int decrement (){
If (-- counter <0 ){
Counter = 0;
}
Return counter;
}
}
Every Java object can have the most one monitor. When a thread accesses its synchronized method, it only allows one thread to access it at a time, so that other threads can wait in queue. In this way, multithreading can avoid damages to shared data. Remember that synchronized will consume system resources to reduce program execution efficiency. Therefore, you must use synchronized only when synchronization is required, especially in the development of j2s. If you want the thread to wait for the occurrence of an event and continue to execute it, it involves thread scheduling. In Java, wait (), Y (), and yyall () are implemented. These three methods are defined in the object class, call OBJ when you want to suspend the thread. the wait () method calls notify () on the same OBJ to restart the thread.
Finally, we end this article with the example of producer/consumer provided by Sun. The content is that producer generates a number and consumer consumes this number. This applet basically covers all the knowledge points in this article. Please study the code in detail
Public class producer extends thread {
Private cubbyhole;
Private int number;
Public producer (cubbyhole C, int number ){
Cubbyhole = C;
This. Number = number;
}
Public void run (){
For (INT I = 0; I <10; I ++ ){
Cubbyhole. Put (I );
System. Out. println ("producer #" + this. Number
+ "Put:" + I );
Try {
Sleep (INT) (math. Random () * 100 ));
} Catch (interruptedexception e ){}
}
}
}
Public class cubbyhole {
Private int contents;
Private Boolean available = false;
Public synchronized int get (){
While (available = false ){
Try {
Wait ();
} Catch (interruptedexception e ){}
}
Available = false;
Policyall ();
Return contents;
}
Public synchronized void put (INT value ){
While (available = true ){
Try {
Wait ();
} Catch (interruptedexception e ){}
}
Contents = value;
Available = true;
Policyall ();
}
}
Public class Consumer extends thread {
Private cubbyhole;
Private int number;
Public consumer (cubbyhole C, int number ){
Cubbyhole = C;
This. Number = number;
}
Public void run (){
Int value = 0;
For (INT I = 0; I <10; I ++ ){
Value = cubbyhole. Get ();
System. Out. println ("Consumer #" + this. Number
+ "Got:" + value );
}
}
}
public class ProducerConsumerTest { public static void main(String[] args) { CubbyHole c = new CubbyHole(); Producer p1 = new Producer(c, 1); Consumer c1 = new Consumer(c, 1); p1.start(); c1.start(); }}
Sun said that the output result should be in the following format, but this is not the case on my machine. Some changes are correct. If you are interested, you can run it and check the result, welcome to discuss with me!
Producer #1 put: 0
Consumer #1 got: 0
Producer #1 put: 1
Consumer #1 got: 1
Producer #1 put: 2
Consumer #1 got: 2
Producer #1 put: 3
Consumer #1 got: 3
Producer #1 put: 4
Consumer #1 got: 4
Producer #1 put: 5
Consumer #1 got: 5
Producer #1 put: 6
Consumer #1 got: 6
Producer #1 put: 7
Consumer #1 got: 7
Producer #1 put: 8
Consumer #1 got: 8
Producer #1 put: 9
Consumer #1 got: 9