The lock () implementation provides a wider range of locking operations than using synchronized methods and statements.
Private lock Lock =new reentrantlock ();
The code to be locked is included with Lock.lock () Lock.unlock (). One with Try ... Finally surround
Synchronization: Low efficiency, deadlock occurs if synchronous nesting occurs. But safe.
Deadlock problem: Two or more than two threads in the process of contention for resources, a kind of mutual waiting phenomenon occurred
Inter-thread communication, the operation of different kinds of threads against the same resource.
Multithreading can also occur multiple times with the same data, or output mismatch problems. are thread-safe issues.
Wait for wake-up mechanism
Wait () in the object class waits for Notify () to wake up a single thread notifyall () wakes all threads
These method calls must be called through the lock object, and the lock object we just used is an arbitrary lock object.
Wait () to be surrounded by a try catch with Wake notify () to resolve the deadlock
That is, a run () determines a condition if it is set on a lock call to wait (), if not set, the lock's judging condition changes and then calls notify () to wake up.
Run state diagram:
Thread groups: The main thread GROUP by default
Getthreadgroup () Get thread Group
Thread.CurrentThread (). Getthreadgroup (). GetName (); Returns the name of the thread group.
Changing thread groups
First create a thread group: Threadgroup tg=new Threadgroup ("This is a new thread group");
Then thread t1=new thread (Tg,myrunnale, "thread name");
Set a background thread through the thread group name, Tg.setdaemon () sets the daemon thread. Wait a minute
Thread groups are primarily thread-unified management.
Synchronization can also be in the class, the corresponding method is set to synchronized note the lock object inside the method is this
Thread Pool: Program startup A new thread cost is relatively high because it involves interacting with the operating system, and two using the thread pool can improve performance, especially if you want to consider using thread pooling when you are creating a lot of short-lived threads in your program.
The thread pool will not be destroyed when it ends, but back to the thread pool to become idle.
-
static ExecutorService |
newCachedThreadPool() Create a thread pool that can create new threads as needed, but reuse them when previously constructed threads are available. |
-
static ExecutorService |
newFixedThreadPool(int nThreads) Create a thread pool that reuses the number of fixed threads and run them in a shared, unbounded queue. |
static ExecutorService |
newSingleThreadExecutor() Create a Executor that uses a single worker thread to run the thread in a unbounded queue. |
A: Create a thread pool object that controls the creation of several thread objects
Executorservoce newfixedthreadpool (int nthread)
B: Threads of this thread pool can execute:
Can execute Runnable object or thread represented by callable object
Make an implementation runnable interface
C: Call the following method:
Future<?> Submit (Runnable Task)
<T> future<t> Submit (callable<t> Task)
Newfixedthreadpool static functions, calling directly
1 executorservice pool=executors.newfixedthreadpool (2); 2 pool.submit (new myrunnable);
- End thread pool: Pool.shutdown ();
- Create multithreaded Mode 3:
Callable is an interface this line threads returns an interface, but Runnable does not return a result. Similar to runnable usage
He is creating threads through the line pool. It's not common.
- The future represents the result of the submit asynchronous calculation. It provides a way to check whether the calculation is complete, to wait for the calculation to complete, and to get the results of the calculation. You can only use the get method to get the results after the calculation is complete and, if necessary, block this method before the calculation is complete. Cancellation is performed by the cancel method. Trouble, generally not.
- Anonymous internal classes use multithreading "
1 //integrating the thread class to implement multithreading2 NewThread () {3 Public voidrun () {4 for(inti = 0; I < 100; i++) {5System.out.println (Thread.CurrentThread (). GetName () + ":" +i);6 }7 };8 }.start ();9//implemented with runnable interfaceTenNewThread (NewRunnable () { One A @Override - Public voidrun () { -//TODO auto-generated Method Stub the for(inti = 0; I < 100; i++) { -System.out.println (Thread.CurrentThread (). GetName () + ":" +i); - } - } +}) {}.start ();
- But for, the child that walks is, will output world, will not output hello
1 NewThread (NewRunnable () {2 3 @Override4 Public voidrun () {5//TODO auto-generated Method Stub6 for(inti = 0; I < 100; i++) {7System.out.println ("Hello" + ":" +i);8 }9 }Ten }){ One Public voidrun () { A for(inti = 0; I < 100; i++) { -SYSTEM.OUT.PRINTLN ("World" + ":" +i); - } the }; -}.start ();
To do something or to repeat something at a specified time.
Timer a tool that a thread uses to schedule tasks to perform later in a background thread. You can schedule a task to execute once, or repeat it periodically.
- Two classes of timer and TimerTask dependent
Timer Timer
TimerTask: Task
-
? Construction Method Summary |
Timer() Creates a new timer. |
|
Timer method
|
cancel() Terminates this timer, discarding all currently scheduled tasks. |
int |
purge() Removes all canceled tasks from this timer's task queue. |
void |
schedule(TimerTask task, Date time) Schedules the specified task to execute at the specified time. |
void |
schedule(TimerTask task, Date firstTime, long period) Schedules the specified task to begin repeating fixed deferred execution at a specified time. |
void |
schedule(TimerTask task, long delay) Schedules the specified task to execute after a specified delay. |
void |
schedule(TimerTask task, long delay, long period) Schedules the specified task to start repeating fixed deferred execution from the specified delay. |
void |
scheduleAtFixedRate(TimerTask task, Date firstTime, long period) Schedules the specified task to start at a fixed rate of repetition at a specified time. |
void |
scheduleAtFixedRate(TimerTask task, long delay, long period) Schedules the specified task to begin repeating a fixed rate of execution after a specified delay.
|
- Interview questions
1: There are several implementations of multithreading, which are the different?two kinds. Inheriting the thread class implements a runnable interface extension: implements the callable interface. This has to be combined with the thread pool. 2: There are several ways to sync, what are the differences?two kinds. Synchronous code block synchronization method3: Start a thread is run () or start ()? What are their differences?start (); Run (): encapsulates the code executed by the thread, calling only the normal method call Start (): Starting the thread and automatically invoking the run () method by the JVM4: The difference between the sleep () and wait () methods sleep (): must refer to time; Wait (): You can specify a time or time, or release a lock. 5: Why Wait (), notify (), Notifyall () are defined in the object class because the calls to these methods are dependent on the lock object, and the lock object of the synchronous code block is any lock. and object code arbitrary objects, so, defined in this face. 6: Thread's life cycle diagram new--ready--run--Death New--ready--run--block--ready--run--Death advice: drawing explanations.