java 多线程 常用java.util.concurrent

本文通过三个示例探讨了Java中线程与并发的具体实现方式,包括不使用ThreadLocal时的线程间变量共享问题、利用ThreadLocal解决线程安全问题,以及ArrayBlockingQueue和Semaphore在并发控制中的应用。
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();} }









                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值