java多線程實例

Java的多線程機制

實例一:

//題目:有三個線程分別打印A、B、C,請用多線程編程實現,在屏幕上循環打印10次ABCABC…

public class SleepExample extends Thread {   
   
    private static int currentCount = 0;   
   
    public SleepExample(String name) {   
        this.setName(name);   
    }     
    @Override 
    public void run() {   
        while (currentCount < 30) {   
            switch (currentCount % 3) {   
            case 0:   
                if ("A".equals(getName())) {   
                	 System.out.print("A");
                	 currentCount++;
                }   
                break;   
            case 1:   
                if ("B".equals(getName())) {   
                	 System.out.print("B");
                	 currentCount++;
                }   
                break;   
            case 2:   
                if ("C".equals(getName())) {   
                	 System.out.print("C");
                	 currentCount++;
                }   
                break;   
            }   
        }   
   
    }     
    public static void main(String[] args) {   
        new SleepExample("A").start();   
        new SleepExample("B").start();   
        new SleepExample("C").start();   
    }   
   
}

實例二:

//編寫一個程序使兩個線程陷入死鎖

public class DeadlockExample {
    String resource1 = "資源1";
    String resource2 = "資源2";
    Thread t1 = new Thread("線程1") {
        public void run() {
            while (true) {
                synchronized (resource1) {
                    synchronized (resource2) {
                        System.out.println("線程1擁有"+resource1+" 需要"+resource2);
                    }
                }
            }
        }
    };
    Thread t2 = new Thread("線程2") {
        public void run() {
            while (true) {
                synchronized (resource2) {
                    synchronized (resource1) {
                        System.out.println("線程2擁有"+resource2+" 需要"+resource1);
                    }
                }
            }
        }
    }; 
    public static void main(String a[]) {
    	DeadlockExample test = new DeadlockExample();
        test.t1.start();
        test.t2.start();
    } 
}

實例三:

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;

//一個線程打印 1~52,另一個線程打印字母A-Z。打印順序爲12A34B56C……5152Z

public class ThreadCommunicationTest {  
   
    private final Lock lock = new ReentrantLock();  
   
    private final Condition conditionA = lock.newCondition();  
    private final Condition conditionB = lock.newCondition();  
   
    private static char currentThread = 'A';  
   
    public static void main(String[] args) {  
   
        ThreadCommunicationTest test = new ThreadCommunicationTest();  
   
        ExecutorService service = Executors.newCachedThreadPool();  
   
        service.execute(test.new RunnableA());  
        service.execute(test.new RunnableB());  
   
        service.shutdown();  
   
    }  
   
    private class RunnableA implements Runnable {  
   
        public void run() {  
            for (int i = 1; i <= 52; i++) {  
                lock.lock();  
   
                try {  
                    while (currentThread != 'A') {  
                        try {  
                            conditionA.await();  
                        } catch (InterruptedException e) {  
                            // TODO Auto-generated catch block  
                            e.printStackTrace();  
                        }  
                    }  
   
                    System.out.println(i);  
                    if (i % 2 == 0) {  
                        currentThread = 'B';  
                        conditionB.signal();  
                    }  
                } finally {  
                    lock.unlock();  
                }  
            }  
   
        }  
   
    }  
   
    private class RunnableB implements Runnable {  
   
        @Override 
        public void run() {  
            for (char c = 'A'; c <= 'Z'; c++) {  
                lock.lock();  
                try {  
                    while (currentThread != 'B') {  
                        try {  
                            conditionB.await();  
                        } catch (InterruptedException e) {  
                            // TODO Auto-generated catch block  
                            e.printStackTrace();  
                        }  
                    }  
   
                    System.out.println(c);  
                    currentThread = 'A';  
                    conditionA.signal();  
                } finally {  
                    lock.unlock();  
                }  
            }  
   
        }  
   
    } 
}


多線程詳解請參考http://blog.sina.com.cn/s/blog_6d5c82a70100m30t.html


j_0006.gif

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章