In the previous article to introduce Java multithreading implementation, through this article to introduce Java multithreaded instances, Java multithreading interested friends to study together
First of all, let's say the pros and cons of multithreading
The advantages of Multithreading:
1) Better utilization of resources
2 programming is simpler in some cases
3 Program Response faster
The cost of Multithreading:
1 Design more complex
While some multithreaded applications are simpler than single-threaded applications, others are generally more complex. This part of the code requires special attention when multithreaded access to shared data. The interaction between threads is often very complex. Errors generated by incorrect thread synchronization are very difficult to discover and reproduce to fix.
2) The cost of context switching
When the CPU switches from executing a thread to executing another thread, it needs to store the current thread's local data, the program pointer, and so on, and then load the local data of another thread, the program pointer, and so on, and finally start executing. This switch is referred to as "context switching" ("contextual switch"). The CPU executes a thread in one context and then switches to another context to execute another thread. Context switching is not cheap. If not necessary, you should reduce the occurrence of context switches.
There are two key technologies for defining and starting threads:
First: The thread class must implement the Java.lang.Runnable interface or inherit the Java.lang.Thread class and implement the Run method, where the Run method has no input, no output, and no exception.
Second: Call the Start method of the thread class to initiate the thread, and when CPU resources are obtained, the Start method automatically invokes the thread-run method to start running.
Package test;
Import Java.util.Vector;
Import java.util.Date;
/**
* Thread Test instance
* @author Still water * */public
class threadnew
{
/**
* *
* @author Still Water
* *
*
/class Threada extends Thread
{
private Date runtime;
public void Run ()
{
System.out.println ("Threada begin.");
This.runtime = new Date ();
System.out.println ("Threada end.");
}
/**
* *
@author still water * */
class Threadb implements Runnable
{
private Date runtime;
public void Run ()
{
System.out.println ("THREADB begin.");
This.runtime = new Date ();
System.out.println ("threadb end.");
}
/**
*
*/public
void Starta ()
{
Thread Threada = new Threada ();
Threada.start ();
}
/**
*
*
/public void STARTB ()
{
Runnable threadb = new threadb ();
Thread thread = new Thread (THREADB);
Thread.Start ();
}
/**
*
* @param args
/public static void main (string[] args)
{
threadnew test = new Threadnew ();
Test.starta ();
TEST.STARTB ();
}