1. The producer-consumer problem
public class Test {
public static void main(String[] args) {
Queue q=new Queue();
new Thread(new 生产者(q)).start();
new Thread(new 消费者(q)).start();
}
}
//缓冲区
class Queue{
String name;
String tool;
}
class 生产者 implements Runnable {
生产者(Queue q){
this.q=q;
}
Queue q;
public void run() {
int i=0;
while(true){
synchronized(q)
{
if(i%2==0){
q.name="鸡蛋";
try{Thread.sleep(10);}catch(Exception ex){}
q.tool="平底锅";
}
else{
q.name="核桃";
q.tool="锤子";
}
i=(i+1)%2; //让i 进行切换
}
}
}
}
class 消费者 implements Runnable {
Queue q;
消费者(Queue q){
this.q=q;
}
public void run() {
while(true){
synchronized(q)
{
System.out.print(q.name);
try{Thread.sleep(10);}catch(Exception ex){}
System.out.println("-" + q.tool);
}
}
}
}
For the above procedures, the output for the
eggs - pan
Eggs - pan
Eggs - pan
walnut - hammer
walnut - Hammer
walnut - Hammer
walnut - hammer
eggs - pan
Eggs - pan
Eggs - pan
to complete two threads collaboration is necessary to use communications thread
2. communication between threads
--wait () tells the current thread to give up the lock (Object Monitor), waits until it receives notification notify this to continue in the locked
--notify () notification wait for the lock thread starts running
--notifyAll notification waiting for the lock All threads start running
Rewrite the program producers and consumers
public class Test {
public static void main(String[] args) {
Queue q=new Queue();
new Thread(new 生产者(q)).start();
new Thread(new 消费者(q)).start();
}
}
//缓冲区
class Queue extends Object{
String name;
String tool;
boolean 有东西=false;
}
class 生产者 implements Runnable {
生产者(Queue q){
this.q=q;
}
Queue q;
public void run() {
int i=0;
while(true){
synchronized(q)
{
if(q.有东西==true){
try{q.wait();}catch(Exception ex){}
}
if(i%2==0){
q.name="鸡蛋";
try{Thread.sleep(10);}catch(Exception ex){}
q.tool="平底锅";
}
else{
q.name="核桃";
q.tool="锤子";
}
q.有东西=true;
q.notify(); //通知消费者过来取
i=(i+1)%2; //让i 进行切换
}
}
}
}
class 消费者 implements Runnable {
Queue q;
消费者(Queue q){
this.q=q;
}
public void run() {
while(true){
synchronized(q)
{
if(q.有东西==false){
try{q.wait();}catch(Exception ex){}
}
System.out.print(q.name);
try{Thread.sleep(10);}catch(Exception ex){}
System.out.println("-" + q.tool);
q.有东西=false;
q.notify();
}
}
}
}
3. The optimization program producers and consumers
public class Test {
public static void main(String[] args) {
Queue q=new Queue();
new Thread(new 生产者(q)).start();
new Thread(new 消费者(q)).start();
}
}
class Queue{ // Queue 是一个线程安全的类
String name;
String tool;
boolean 有东西=false;
//放东西
synchronized public void put(String name,String tool){
if(this.有东西){
try{this.wait();}catch(Exception ex){}
}
this.name=name;
this.tool=tool;
this.有东西=true;
this.notify();
}
//取东西
synchronized public void get(){
if(this.有东西==false){
try{this.wait();}catch(Exception ex){}
}
System.out.print(this.name);
System.out.println("-" +this.tool);
this.有东西=false;
this.notify();
}
}
class 生产者 implements Runnable{
生产者(Queue q){
this.q=q;
}
Queue q;
public void run() {
int i=0;
while(true){
if(i%2==0){
q.put("鸡蛋", "平底锅");
}
else{
q.put("核桃", "锤子");
}
i=(i+1)%2;
}
}
}
class 消费者 implements Runnable{
消费者(Queue q){
this.q=q;
}
Queue q;
public void run() {
while(true){
q.get();
}
}
}
4. thread termination
An end flag) set of threads
2) interupt ();
. 3) STOP (); // discarded, prone to deadlocks
class Test{
public static void main(String[] args) {
EmpThread empThread=new EmpThread();
new Thread(empThread).start();
for (int i = 0; i < 100; i++) {
if(i==90){
empThread.stopMe(true);
}
System.out.println("领导正在讲第话 第"+i +"句");
}
}
}
class EmpThread implements Runnable
{
private boolean isStop;
public void stopMe(boolean isStop){
this.isStop=isStop;
}
public void run(){
while(isStop==false){
System.out.println("员工在鼓掌..");
}
}
}
5. background thread
Methods
public final void setDaemon (boolean on)
if the transfer ture, then a thread, set to a background thread, before calling to online Chengkai Qi
background thread (also known as a daemon thread, elves thread)
systems can run simultaneously with the foreground thread, and background thread,
when the system does not run the foreground thread, java virtual machine exit
6.JDK 1.5 after java.util.concurrent.locks
Since that JDK1.5, Java provides java.util.concurrent this contract and in its sub-package locks in,
provides a series of locks on the abstract class. There are two main lock
ReentrantLock // a reentrant mutex Lock, it has the same implicit monitor lock some basic behavior and semantics using synchronized methods and statements are visiting, but more powerful
ReentrantReadWriteLock // support and ReentrantLock ReadWriteLock achieve similar semantics. (ReadWriteLock // maintains a pair of associated locks, one for the read-only operations, one for writing.)
While the other two classes are "helper" type,
as is AbstractQueuedSynchronizer for implementing a special rules lock abstract class, ReentrantLock and internal ReentrantReadWriteLock have an inner class that inherits the abstract class,
used to achieve a particular lock functions. It describes the following: ReentrantReadWriteLock ReentrantLock and
attached: Reentrant word, the meaning is reentrant
// reentrant lock ReentrantLock
using a simple lock ReentrantLock example:
Lock Lock ReentrantLock new new = ();
{the try
lock.lcok ();
// do something
} {the finally
lock.unlock ();
}
The above code, first creates a Lock, which then calls the lock () method, open lock, call it in the final unlock () unlock.
When Notably, the use of locks in general, should be written according to the above style codes, i.e. lock.unlock () is preferably placed in the finally block, which can be prevented,
the exception occurs while executing do something, it causes lock never be freed.
Lock and synchronized difference:
1) Lock to complete almost all the synchronized function, and there are some who do not have features such as lock poll, timed lock wait, wait interruptible lock, etc.
2) synchronized Java language level, is the built-in keyword; Lock JDK 5 is a packet appearing, in use, the synchronized
code blocks may be automatically released by the synchronization JVM; Lock requires the programmer to manually release the finally block, if not released, can cause unpredictable consequences (in multiple threaded environment).
Lock is an abstract framework for locking, which allows locked implemented as Java classes, rather than as a language feature to achieve.
This is the realization of a variety Lock left a space, various implementations may have different scheduling algorithms, performance characteristics, or locking semantics
3) synchronized implementation mechanism is relatively old, the earlier design, there are some functional limitations:
= = it can not interrupt a thread is waiting to acquire a lock
== lock could not get through to vote, you do not want to wait, it can not be locked.
== also requires synchronization lock release the lock can only be obtained with the same stack frame where the stack frame
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class Test{
public static void main(String[] args) throws InterruptedException {
SaleThread s =new SaleThread();
new Thread(s).start();
new Thread(s).start();
new Thread(s).start();
new Thread(s).start();
}
}
class SaleThread implements Runnable{
int ticket=100;
Lock lock=new ReentrantLock(); //注意,多个线程要共用同一个锁
public void run(){
while(true){
lock.lock();
try{
if(ticket>0){
try{Thread.sleep(10);}catch(Exception e){}
System.out.println("线程 "+Thread.currentThread().getName()+"正在卖第"+ticket-- +"张票" );
}
else{
break;
}
}
catch(Exception ex){
ex.printStackTrace();
}
finally{
lock.unlock();
}
}
}
}