1、线程thread中有几个方法来对线程进行控制:下面介绍几个比较经常使用到的java
方法 | 介绍 |
---|---|
join | 等待某个线程执行完成之后,在执行另外一个线程 |
sleep | 让某个线程睡眠某个时间 |
yield | 让某一个线程稍等一下 |
下面是一个join方法例子:git
package org.pan.duoxian.cheng.pojos; public class PrintCharJoin implements Runnable{ private Character c; private Integer i; public PrintCharJoin(Character c, Integer i) { super(); this.c = c; this.i = i; } @Override public void run() { Thread t4 = new Thread(new PrintNum(2000, 100)); t4.start(); for(int j=0;j<i;j++){ if(j==60){ try { t4.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.print(this.c+""+j+","); } } }
2、线程的同步dom
线程的同步有三种方式:ide
一、synchronized关键字:synchronized能够加到方法里或者某个资源上来同步线程。工具
package org.pan.duoxian.cheng.main; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * 利用synchronized关键字加同步锁的两种方式 * @author Administrator * */ public class TestAcount { private static Account account = new Account(); public static void main(String[] args) { ExecutorService executor = Executors.newCachedThreadPool(); for(int i=0;i<100;i++){ System.out.println("-----------------这是第"+i+"个线程"); executor.execute(new AddPenny(i)); } executor.shutdown(); while(!executor.isTerminated()){ } System.out.println(account.getBalance()); } public static class AddPenny implements Runnable{ private int order; public AddPenny(int order) { super(); this.order = order; } @Override public void run() { account.desposit(1,order); //同步的其余方法,同步资源 // synchronized (account) { // account.desposit(1,order); // } } } public static class Account{ private int balance = 0; public int getBalance() { return balance; } //将方法同步 public synchronized void desposit(int amount, int order){ int newBalance = this.balance + amount; System.out.println(order+"号线程>>>>>>>>>>>>>>>>进入休眠前"+newBalance); try { Thread.sleep(1); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } this.balance = newBalance; System.out.println(order+"号线程<<<<<<<<<<<<<<<<<<进入休眠后"+balance); } } }
二、Lock同步锁ui
package org.pan.duoxian.cheng.main; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * 利用lock加锁同步 * @author Administrator * */ public class TestAcountLock { private static Account account = new Account(); public static void main(String[] args) { ExecutorService executor = Executors.newCachedThreadPool(); for(int i=0;i<100;i++){ System.out.println("-----------------这是第"+i+"个线程"); executor.execute(new AddPenny(i)); } executor.shutdown(); while(!executor.isTerminated()){ } System.out.println(account.getBalance()); } public static class AddPenny implements Runnable{ private int order; public AddPenny(int order) { super(); this.order = order; } @Override public void run() { account.desposit(1,order); } } public static class Account{ private static Lock lock = new ReentrantLock(); private int balance = 0; public int getBalance() { return balance; } public void desposit(int amount, int order){ lock.lock(); System.out.println(order+"号线程>>>>>>>>>>>>>>>>进入休眠前"+balance); int newBalance = this.balance + amount; try { Thread.sleep(1); this.balance = newBalance; System.out.println(order+"号线程<<<<<<<<<<<<<<<<<<进入休眠后"+balance); } catch (InterruptedException e) { e.printStackTrace(); }finally{ lock.unlock(); } } } }
三、Semaphore信号量this
package org.pan.duoxian.cheng.main; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; /** * 利用线程管理线程 * @author panmingshuai * @date 建立时间:2017年8月1日 下午10:48:30 */ public class TestAccountSemaphore { private static Account account = new Account(); public static void main(String[] args) { ExecutorService executor = Executors.newCachedThreadPool(); for(int i=0;i<100;i++){ System.out.println("-----------------这是第"+i+"个线程"); executor.execute(new AddPenny(i)); } executor.shutdown(); while(!executor.isTerminated()){ } System.out.println(account.getBalance()); } public static class AddPenny implements Runnable{ private int order; public AddPenny(int order) { super(); this.order = order; } @Override public void run() { account.desposit(1,order); } } public static class Account{ private static Semaphore semaphore = new Semaphore(1); private int balance = 0; public int getBalance() { return balance; } public void desposit(int amount, int order){ try { semaphore.acquire(); System.out.println(order+"号线程>>>>>>>>>>>>>>>>进入休眠前"+balance); int newBalance = this.balance + amount; Thread.sleep(1); this.balance = newBalance; System.out.println(order+"号线程<<<<<<<<<<<<<<<<<<进入休眠后"+balance); } catch (InterruptedException e) { e.printStackTrace(); }finally{ semaphore.release(); } } } }
3、线程之间怎么通讯spa
线程之间可经过Lock对象获得的condition对象通讯.net
package org.pan.duoxian.cheng.main; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * 利用condition进行线程间通讯 * @author panmingshuai * @date 建立时间:2017年8月1日 下午10:49:14 */ public class TestAccountCondition { private static Account account = new Account(); public static void main(String[] args) { ExecutorService excutor = Executors.newFixedThreadPool(2); excutor.execute(new Withdraw()); excutor.execute(new Desposit()); excutor.shutdown(); } public static class Desposit implements Runnable{ @Override public void run() { try { while(true){ account.deposit((int)(Math.random()*10)+1); Thread.sleep(1000); } } catch (Exception e) { // TODO: handle exception } } } public static class Withdraw implements Runnable{ @Override public void run() { while(true){ account.withdraw((int)(Math.random()*10) + 1); } } } private static class Account{ private Lock lock = new ReentrantLock(); private Condition condition = lock.newCondition(); private int balance = 0; public int getBalance() { return balance; } public void withdraw(int amount){ lock.lock(); System.out.println("须要取:"+amount); try { System.out.println("取钱以前有:"+balance); while(balance<amount){ condition.await(); } System.out.println("不在等待,取钱以前有:"+balance); balance -= amount; System.out.println("取钱以后有:"+balance); } catch (Exception e) { e.printStackTrace(); }finally { lock.unlock(); } } public void deposit(int amount){ lock.lock(); System.out.println("存了:"+amount); try { balance += amount; System.out.println("存钱以后有:"+balance); condition.signalAll(); } catch (Exception e) { e.printStackTrace(); }finally { lock.unlock(); } } } }
4、消费者和生产者的例子:线程
package org.pan.duoxian.cheng.main; import java.util.LinkedList; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * 利用condition完成消费者和生产者 * @author panmingshuai * @date 建立时间:2017年8月1日 下午10:49:50 */ public class ConsumerProducer { private static Buffer buffer = new Buffer(); public static void main(String[] args) { ExecutorService excutor = Executors.newFixedThreadPool(2); excutor.execute(new ProducerTask()); excutor.execute(new ConsumerTask()); excutor.shutdown(); } public static class ProducerTask implements Runnable{ @Override public void run() { try { int i = 0; while(true){ buffer.write(i++); Thread.sleep((int)(Math.random()*2000)); } } catch (Exception e) { e.printStackTrace(); } } } public static class ConsumerTask implements Runnable{ @Override public void run() { try { while(true){ buffer.read(); Thread.sleep((int)(Math.random()*2000)); } } catch (Exception e) { e.printStackTrace(); } } } private static class Buffer{ private static int CAPASITY = 2; private LinkedList<Integer> queue = new LinkedList<>(); private Lock lock = new ReentrantLock(); private Condition notfull = lock.newCondition(); private Condition notempty = lock.newCondition(); public void write(int value){ lock.lock(); try { while(queue.size() == CAPASITY){ notfull.await(); } queue.offer(value); System.out.println("写入了:"+value); notempty.signal(); } catch (Exception e) { e.printStackTrace(); }finally { lock.unlock(); } } public int read(){ int value = 0; lock.lock(); try { while(queue.isEmpty()){ notempty.await(); } value = queue.remove(); System.out.println("取走了:"+value); notfull.signal(); } catch (Exception e) { e.printStackTrace(); }finally { lock.unlock(); } return value; } } }
6、死锁的例子:
package org.pan.duoxian.cheng.main; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * 死锁的例子 * @author panmingshuai * @date 建立时间:2017年8月1日 下午10:55:22 */ public class TestDeadLock { private static Account account = new Account(); public static void main(String[] args) { ExecutorService excutor = Executors.newFixedThreadPool(2); excutor.execute(new Withdraw()); excutor.execute(new Desposit()); excutor.shutdown(); } public static class Desposit implements Runnable{ @Override public void run() { try { while(true){ account.deposit((int)(Math.random()*10)+1); Thread.sleep(1000); } } catch (Exception e) { // TODO: handle exception } } } public static class Withdraw implements Runnable{ @Override public void run() { while(true){ account.withdraw((int)(Math.random()*10) + 1); } } } private static class Account{ private Lock lockBalance = new ReentrantLock(); private Lock lockWater = new ReentrantLock(); private int balance = 0; private int water = 0; public int getBalance() { return balance; } public int getWater() { return water; } public void withdraw(int amount){ try { lockBalance.lock(); System.out.println("withdraw:get:balance"); Thread.sleep(1000); lockWater.lock(); Thread.sleep(1000); System.out.println("withdraw:get:water"); } catch (Exception e) { e.printStackTrace(); }finally { lockWater.unlock(); lockBalance.unlock(); } } public void deposit(int amount){ try { lockWater.lock(); Thread.sleep(1000); System.out.println("desposit:get:water"); lockBalance.lock(); Thread.sleep(1000); System.out.println("desposit:get:balance"); } catch (Exception e) { e.printStackTrace(); }finally { lockBalance.unlock(); lockWater.unlock(); } } } }
上述的例子能够直接拷到工具里运行,只须要改改包名就好了
若是仍是以为麻烦,马云的地址为:https://git.oschina.net/panmingshuai/cheng.git