thread creates two methods of threading:
1. Define class Inheritance thread class, overwrite the Run method in class, invoke the Start method of class object, Start method starts thread, call run method. The thread class is used to describe threads; This class defines a function run that stores the code that the thread is running.
2, the definition class implements the Runnable interface, overwrites the Runnable interface method, constructs the thread object through the thread class, passes the subclass object of the Runnable interface as the actual parameter to the thread class constructor, and invokes the thread class's Start method to open the threads , the thread invokes the Run method in the Runnable interface subclass;
The way to implement interface runnable avoids the limitation of single inheritance;
Thread T;
T.setmaemon (TRUE);/set thread as background thread; Background thread ends automatically when all foreground threads end;
T.notify ();//wake this thread;
T.notifyall ();//wake up all threads;
T.interrupt ();//Middle thread;
Thread.Sleep (100);/Pause thread 100 ms
synchronized: The default lock is itself, you can also lock the custom object;
Must have two and more threads to execute, multiple threads using the same lock, must ensure that the synchronization process can only have a thread running;
To determine the synchronization: clear what code is required to run a multithreaded code, clear sharing of data, clear multi-threaded running code in which statements are operating shared data;
Class Tickets implements Runnable
{
private int tick = 100;
public void Run () {//Public synchronized void run ()
while (tick > 0) {
Synchronized (this) {
if (Tick > 0) {
try {
Thread.Sleep (100);
catch (Interruptedexception e) {
E.printstacktrace ();
}
System.out.println (this.tostring () + "Sale:" + tick--);
}
}
}
}
As above: Tick is to share data, operation Tick need to operate in synchronized, synchroized lock is tickets itself;
wait for wake mechanism: When the synchronization thread is being manipulated, must identify the locks held by the threads they operate on, and only the waiting thread of the same lock can be awakened by the notify of the same lock, and the threads in different locks cannot be awakened; (i.e., wait and wake must be the same lock )