package com.pateo.api;
public class TestWithNoThreadLocal {
public static int a = 0;
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start();
MyThread myThread2 = new MyThread();
myThread2.start();
}
public static class MyThread extends Thread {
public void run() {
for (int i = 0; i < 5; i++) {
a = a + 1;
System.out.println(Thread.currentThread().getName() + ":" + a);
}
}
}
}
package com.pateo.api;
import com.pateo.api.TestWithNoThreadLocal.MyThread;
public class TestThreadLocal {
private static ThreadLocal<Integer> a = new ThreadLocal<Integer>() {
public Integer initialValue() { // 初始化,默认是返回 null
return 0;
}
};
public static void main(String args[]) {
MyThread my = new MyThread();
my.start();
MyThread myThread2 = new MyThread();
myThread2.start();
}
public static class MyThread extends Thread {
public void run() {
for (int i = 0; i < 5; i++) {
a.set(a.get() + 1);
System.out.println(Thread.currentThread().getName() + ":"
+ a.get());
}
}
}
}
import java.util.concurrent.ArrayBlockingQueue; public class TestArrayBlockQueue { private ArrayBlockingQueue<Integer> mQueue = new ArrayBlockingQueue<Integer>(5); private final class EventThread extends Thread { public EventThread(){ super("EventThread"); } public void run(){ while(true){ try{ mQueue.take(); }catch(InterruptedException ie) { } System.out.println("---------------------------------------"); } } } private void add() throws InterruptedException{ mQueue.put(1); } public void play() throws InterruptedException{ EventThread mEventThread = new EventThread(); mEventThread.start(); Thread.sleep(3000); } public static void main(String[] args) throws InterruptedException { TestArrayBlockQueue tab = new TestArrayBlockQueue(); tab.play(); //tab.add(); } }
package com.pateo.api;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;public
class TestSemaphore {public static void main(String[] args) {
ExecutorService exec = Executors.newCachedThreadPool();
final Semaphore semp = new Semaphore(2);
for (int index = 0; index < 10; index++) {
final int NO = index;Runnable runable = new Runnable() {
public void run() {
try {
semp.acquire();
System.out.println(Thread.currentThread().getName());Thread.sleep((long) ( 10000));
semp.release();
} catch (InterruptedException e) {}}
};
exec.execute(runable);
}
exec.shutdown();}
}
本文通过三个示例探讨了Java中线程与并发的具体实现方式,包括不使用ThreadLocal时的线程间变量共享问题、利用ThreadLocal解决线程安全问题,以及ArrayBlockingQueue和Semaphore在并发控制中的应用。
168

被折叠的 条评论
为什么被折叠?



