Threads:
static void sleep (long milliseconds): Sleeps in the specified number of milliseconds to put the executing thread into hibernation (paused execution)
Throws Interruptedexception
Attention:
1 thread hibernation is the best way to help all threads get the chance to run
2 thread sleep automatically wakes up and returns to Ready state (can run), not running state.
The time specified by sleep () is the shortest time that can be run after hibernation,
The sleep () method does not guarantee that the thread will start running after it expires
3 Sleep () is a static method that only controls the currently running thread.
Thread priority: The higher the level, the more opportunities. The lower the level, the less the opportunity, but not the absolute
Max: Ten Max_priority
Lowercase: 1 min_priority
Default: 5 norm_priority
SetPriority ()
GetPriority ()
Join (): The merge means that the current thread waits for the thread to finish executing, and if the thread is not finished before sleep, the other threads will no longer wait
Static yield (): current thread concessions. Only one concession at a time, the next is which thread is not necessarily
void Interrupt (): The flag that interrupts the thread interrupt modification flag:false–>true
Static Boolean Interrupted (): Whether the interrupted state returns flag erase True–>false
Main () {
T1 t = new T1 ();
T.start ();
Send out an interrupt signal
T.interrupt ();//thread.interrupted () flag:false–>true
}
Class T1 extends thread{
public void Run () {
while (! Thread.interrupted ()) {
....
If sleep () is interrupted, an exception is thrown
}
SYSTEM.OUT.PRINTLN ("Child Thread End");
}
}
Sync:
Data is not secure:
1 runnable interface for data sharing
2 The shared statement in the Run method consists of multiple lines
3 Run Method blocking
Synchronization mechanism: Sync lock
Indicates that only one thread can execute, the middle cannot be interrupted, and the other threads can wait only
Principle: is actually locking an object
Ways to achieve synchronization:
1) Synchronizing code blocks:
Synchronized (lock) {
}//自动解锁 种类: a 任意对象 Object obj = new Object();//声明了一个锁 synchronized(obj){ } b this:当前对象:将当前对象当成锁 synchronized(this){ } 特殊: synchronized("abc"){ } byte[] b= new byte[]; synchronized(b){//0个长度的字节数组 } c 运行时的锁 静态的数据。静态方法调用的时候使用运行时锁 A.java-->A.class:jvm加载字节码文件 synchronized(XXX.class){ } 2)同步方法:在方法前面加上synchronized关键字 同步非静态方法,锁定是this对象 同步静态方法,锁定是XXX.class对象 ----->同一时刻只有一个线程访问该方法
Instance:
public class Demo {
public static void Main (string[] args) {TicketRunnable1 t = new TicketRunnable1 (); thread T1 = new Thread (t, "A"); Thread t2 = new Thread (t, "B"); T1.start (); try {thread.sleep (100); } catch (Interruptedexception e) {//TODO auto-generated catch block E.printstacktrace (); } T.flag = false; T2.start ();} Static Class TicketRunnable1 implements Runnable {private int tickets = 10; Private Boolean flag = true; private static int sum = 10; @Override public void Run () {if (flag) {while (true) {try {thre Ad.sleep (100); } catch (Interruptedexception e) {//TODO auto-generated catch block e.printstacktr Ace (); } System.out.println ("Sale" + sum--); }} else {while (true) t (); }}//sync method: Lock this public synchronized void sale () {iF (Tickets > 0) {try {thread.sleep (100); } catch (Interruptedexception e) {//TODO auto-generated catch block E.printstacktrace (); } System.out.println (Thread.CurrentThread (). GetName () + "------" +--ticket s); } else {flag = false; }}//Note the granularity of the method//Static synchronization method: Lock the class at the same time only one thread uses this method public static synchronized void T () {//ticketrunnable1.c Lass if (Sum > 0) {try {thread.sleep (100); } catch (Interruptedexception e) {//TODO auto-generated catch block E.printstacktrace (); } System.out.println (Thread.CurrentThread (). GetName () + "------" +--sum); } }}
}
Deadlock:
Because a thread locks resource A, wait for resource B. Thread B Locks resource B, waits for resource A, and there is a deadlock
Another synchronization is initiated in the synchronization code of one thread, and the two thread locks cross-use
Instance:
public class Demo {
public static void Main (string[] args) {myrunnable Mr = new Myrunnable (); Mr.flag = true;//Zhang San thread t1 = new Thread (MR, "Zhang San"); T1.start (); Myrunnable MR1 = new myrunnable (); Mr1.flag = false;//John Doe thread t2 = new Thread (MR1, "John Doe"); T2.start ();} Static Class Myrunnable implements Runnable {private static string bread = "bread";//Resource a private static string milk = "Milk"; Resource B boolean flag; Toggle @Override public void Run () {if (flag) {//Zhang San synchronized (bread) {System.out.pri Ntln (Thread.CurrentThread (). GetName () + "already locked bread, also want milk"); try {thread.sleep (100); } catch (Interruptedexception e) {//TODO auto-generated catch block e.printstacktr Ace (); } synchronized (milk) {System.out.println (Thread.CurrentThread (). GetName () + "has locked the bread also has the milk"); }}} else {//John Doe synchronized (milk) {System.out.println (thread.currentthread (). GetName () + "already locked milk, also want bread"); try {thread.sleep (100); } catch (Interruptedexception e) {//TODO auto-generated catch block e.printstacktr Ace (); } synchronized (bread) {System.out.println (Thread.CurrentThread (). GetName () + "has locked the milk also has the bread"); } } } }}
}
Producer-Consumer model:
Notify () Notifyall () wait () must be in a sync lock to appear.
To indicate that the object holding the thread waits or wakes by a lock.
Object class:
Wait (): Causes the thread to enter the waiting state, puts in the thread pool, releases the lock
Notify (): Wakes a waiting thread, wakes any thread in the thread pool
Notifyall (): Wakes all threads in the thread pool
Roast duck
Whether there is a product: Flag
1) No Products:
if (flag = = false)//no roast duck
Producer Thread Production Products
Flag = true;
Consumer thread Wait
Wait (): Notify the producer to produce the product
2) Products available
if (flag = = True)
Producer Threads: Waiting for consumer spending
Consumer Threads:
Consumption
Flag = False
Producers are responsible for production, production and product tasks
Consumers are responsible for consumption, with the task of consuming products
Production and consumption at the same time-multithreading
Instance:
public class Demo {
public static void Main (string[] args) {
Duck d = new Duck ();
Productor Pro = new Productor (d);
Customer cus = new Customer (d);
Thread T1 = new Thread (PRO);
Thread t2 = new Thread (cus);
T1.start ();
T2.start ();
}
}
class Duck {
String name;
int price;
Boolean flag;//Flag
@Override
Public String toString () {
return "roast duck [name=" + name + ", price=" + pric E + ", flag=" + flag + "]";
}
}
Producers
Class Productor implements Runnable {
Duck Duck;
Productor (Duck Duck) {
This.duck = Duck;
}
@Override
public void Run () {
while (true) {
Synchronized (duck) {
if (Duck.flag) {//There is already a good roast duck now.
try {
Duck.wait ();//Waiting for consumption
} catch (Interruptedexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
Production Products
duck.name = "Beijing roast Duck";
Duck.price = 298;
System.out.println ("———");
System.out.println ("Production of roast Duck:" + duck);
Duck.flag = true; Modified flag: It's ready for production.
Wake-up consumer
Duck.notify ();
}
}
}
}
Consumers
Class Customer implements Runnable {
Duck Duck;
Customer (Duck Duck) {
This.duck = Duck;
}
@Overridepublic void run() { while (true) { synchronized (duck) { if (!duck.flag) {// 没有产品 try { duck.wait(); // 等待生产产品 } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println("吃烤鸭" + duck); System.out.println("-------------"); duck.flag = false;// 修改标志 duck.notify(); } }}
}
public class Demo {
public static void main(String[] args) { Room wdm = new Room(); Pro p = new Pro(wdm); Cus c = new Cus(wdm); new Thread(p).start();// t1 new Thread(c).start(); // t2 new Thread(p).start(); // t3 new Thread(c).start(); // t4}
}
Class. {
private String name;
Private int price;
Private Boolean flag;
Public String GetName () {return name;} public void SetName (String name) {this.name = name;} public int GetPrice () {return price;} public void Setprice (int. price) {this.price = Price;} public Boolean Isflag () {return flag;} public void Setflag (Boolean flag) {This.flag = flag;} Public Guest (String name, int price, Boolean flag) {super (); THIS.name = name; This.price = Price; This.flag = Flag;} Public Guest () {super ();} @Overridepublic String toString () {return "name=" + "+ name +", price= "+ Price +", flag= "+ Flag +"] ";} Production of bread P t1 T3 c t2 t4public synchronized void Productbread (String name, int price) {//already has a product: while instead of if while (f Lag) {try {//System.out.println ("There is currently a product, waiting for consumption ..."); This.wait ();//wait T1 t2 t3} catch (Interruptedexception e) {//TODO auto-generated catch block E.printstacktrace (); }} this.name = name; This.price = Price; System.Out.println ("Production Bread:" + name + "" + price); This.flag = true; This.notifyall ();////////////////////////////}//consumption bread public synchronized void Buybread () {while (!flag) {//No bread try {//System.out.println ("not currently producing good bread, waiting ..."); This.wait (); } catch (Interruptedexception e) {//TODO auto-generated catch block E.printstacktrace (); }} System.out.println ("Consumer Bread:" + name + "" + price); This.flag = false;//consumed, no product this.notifyall ();}
}
Producers
Class Pro implements Runnable {
Hostel R;
Pro(Room r) { this.r = r;}int i = 0;@Overridepublic void run() { while (true) { if (i % 2 == 0) { r.productBread("毛毛虫", 7); } else { r.productBread("面包", 10); } i++; }}
}
Consumers
Class Cus implements Runnable {
Hostel R;
Cus(Room r) { this.r = r;}@Overridepublic void run() { while (true) { r.buyBread(); }}
}
Lock:
Synchronized: Pessimistic lock.
Lock: Optimistic lock.
Synchronized (object) {//Lock
}//Release Lock
Use the lock interface to describe the lock separately.
1 Create a subclass of the lock interface-reentrantlock
Using lock instead of synchronizing blocks of code
2 code that needs to be synchronized is placed between lock () and unlock ()
Wait (), notify (), Notifyall () must appear in the synchronization code
The condition interface provides the appropriate methods,
Await () signal () Signalall ()
Thread pool: Executor
Creating a single-thread pool object
Executor Executor = Executors.newsinglethreadexecutor ();
Executor.execute (New threadrunnable ());
Executor.execute (New threadrunnable ());
Create 2 threads that can be executed at the same time
Executor e = Executors.newfixedthreadpool (2);
E.execute (New threadrunnable ());
E.execute (New threadrunnable ());
E.execute (New threadrunnable ());
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Java Basic notes (v)