public class ThreadDemo { /** * 打印名字 * @param name */ public void showName(String name){ for(int i=0;i<name.length();i++){ System.out.PRint(name.charAt(i)); } System.out.println(); } public static void main(String[] args){ ThreadDemo t=new ThreadDemo(); new Thread(){ @Override public void run() { while(true){ t.showName("鋼鐵俠"); } } }.start(); new Thread(){ public void run() { while(true){ t.showName("美國隊長"); } } }.start(); }}為了解決類似這種情況,應該引入同步的概念,也就是給方法加鎖,當其他線程調用該方法時,如果鎖解開了才能調用,如果沒有,則不能調用。java中同步的關鍵字是synchronzied,如果方法不加鎖,則會出現意想不到的結果。使用synchronzied有兩種方法,這里我舉一個比較省事的方法
public class ThreadDemo { /** * 打印名字 * @param name */ public synchronized void showName(String name){ for(int i=0;i<name.length();i++){ System.out.print(name.charAt(i)); } System.out.println(); } public static void main(String[] args){ ThreadDemo t=new ThreadDemo(); new Thread(){ @Override public void run() { while(true){ t.showName("鋼鐵俠"); } } }.start(); new Thread(){ public void run() { while(true){ t.showName("美國隊長"); } } }.start(); }}TipS:在JDK1.5及以后,在Java.util.concurrent.locks包下面提供了Lock接口,Lock實現提供了比使用synchronized方法和語句可獲得更廣泛的鎖定操作,此實現允許更靈活的結構,可以具有差別很大的屬性。舉個模仿火車票買票系統:假設某一站只有100張火車票,有200個人分別在不同的窗口買票,200人相當于兩百個線程,為了出現有人結賬是被告知票已經賣完的情況,買票的方法需要加上鎖。import java.util.Random;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;public class TicketDemo { private int Ticketcount=100; private static int people=200; private Lock lock = new ReentrantLock(); private static TicketDemo td=new TicketDemo(); public static void main(String[] args) { for (int i = 0; i < people; i++) { new Thread(){ @Override public void run() { super.run(); td.Buy(); } }.start(); } } public void Buy(){ //上鎖 lock.lock(); try { if(Ticketcount == 0){ System.out.println("已賣完"); return; } Random r = new Random(); try { Thread.sleep(r.nextInt(1000)); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("Ticketcount = "+Ticketcount); System.out.println("還剩下:"+(--Ticketcount)+"張票"); } finally { //解鎖 lock.unlock(); } }}二,異步
還拿公交車來講,異步就是大家一起上公交車,因為沒有秩序,也就是說上公交車不收限制。總結:同步其實并不是同時.同步簡單說即使有順序,異步呢,是無序,所以可以同時發生。
新聞熱點
疑難解答