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……5152Zpublic 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
本文出自 “闲庭信步、” 博客,请务必保留此出处http://macxiao.blog.51cto.com/9606147/1591564