當前位置:首頁 » 編程語言 » concurrentinjava

concurrentinjava

發布時間: 2022-05-29 12:33:23

Ⅰ 我想知道java多線程中,如何讓一個線程去等待N個線程執行完成後,再執行。

java.util.concurrent.CountDownLatch 這個類可以實現你所要的功能

例如:CountDownLatch latch = new CountDownLatch(5) //聲明計數器為5個
Thread t = new Thread() {
public void run() {
try {
//TODO 你的應用
} catch (Exception e) {
//TODO 異常處理
}
finally {
latch.countDown(); //這句是關鍵
System.out.println("ok"); //5個線程都跑完後輸出
}
}
};
t.start();
然後讓以上操作循環五次(就是說同時開5個線程),那麼這個"ok"就會在等到這5個線程都ok後才會被輸出一次。

Ⅱ Java多線程之阻塞I/O如何中斷

阻塞的I/O線程在關閉線程時並不會被打斷,需要關閉資源才能打斷。
1.執行socketInput.close();阻塞可中斷。
2.執行System.in.close();阻塞沒有中斷。
復制代碼
package Thread.Interrupting;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class CloseResource {
public static void main(String[] args) throws Exception {
//堵塞的I/O線程不會被打斷,需要關閉資源才能打斷
ExecutorService exec = Executors.newCachedThreadPool();
ServerSocket server = new ServerSocket(8080);
InputStream socketInput = new Socket("localhost", 8080)
.getInputStream();
exec.execute(new IOBlocked(socketInput));
exec.execute(new IOBlocked(System.in));
TimeUnit.MILLISECONDS.sleep(100);
System.out.println("Shutting down all threads");
exec.shutdownNow();
TimeUnit.SECONDS.sleep(1);
System.out.println("Closing " + socketInput.getClass().getName());
socketInput.close();
TimeUnit.SECONDS.sleep(1);
System.out.println("Close " + System.in.getClass().getName());
System.in.close();
}
}
復制代碼

被阻塞的nio通道在關閉線程後會自動響應中斷阻塞,不需要關閉底層資源。
復制代碼
package Thread.Interrupting;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousCloseException;
import java.nio.channels.ClosedByInterruptException;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
class NIOBlocked implements Runnable {
private final SocketChannel sc;
public NIOBlocked(SocketChannel sc) {
this.sc = sc;
}
@Override
public void run() {
try {
System.out.println("Waiting for read() in " + this);
sc.read(ByteBuffer.allocate(1));
} catch (ClosedByInterruptException e) {
System.out.println("ClosedByInterruptException");
} catch (AsynchronousCloseException e) {
System.out.println("AsynchronousCloseException");
} catch (IOException e) {
throw new RuntimeException(e);
}
System.out.println("Exiting NIOBlocked.run() " + this);
}
}
public class NIOInterruption {
public static void main(String[] args) throws Exception {
//被阻塞的nio通道會自動地響應中斷
ExecutorService exec = Executors.newCachedThreadPool();
ServerSocket server = new ServerSocket(8080);
InetSocketAddress isa = new InetSocketAddress("localhost", 8080);
SocketChannel sc1 = SocketChannel.open(isa);
SocketChannel sc2 = SocketChannel.open(isa);
Future<?> f = exec.submit(new NIOBlocked(sc1));

exec.execute(new NIOBlocked(sc2));

exec.shutdown();
TimeUnit.SECONDS.sleep(1);
f.cancel(true);
TimeUnit.SECONDS.sleep(1);
sc2.close();
}
}

Ⅲ 用java編寫程序,利用線程同步編寫一個棧操作程序,包括數據的進棧和出棧。

Stack.java

importjava.util.concurrent.locks.Condition;
importjava.util.concurrent.locks.Lock;
importjava.util.concurrent.locks.ReentrantLock;

publicclassStack{

privateint[]data;
privateintindex;
privateLocklock;
privateConditionmoreSpace;
privateConditionmoreEelment;

publicStack(intsize){
this.data=newint[size];
this.index=0;
this.lock=newReentrantLock();
this.moreSpace=lock.newCondition();
this.moreEelment=lock.newCondition();
}

publicvoidpush(intvalue){
lock.lock();
try{
while(index==data.length){
moreSpace.await();
}
data[index++]=value;
moreEelment.signalAll();
}catch(InterruptedExceptione){
e.printStackTrace();
}finally{
lock.unlock();
}
}

publicintpopup(){
lock.lock();
intvalue=0;
try{
while(index==0){
moreEelment.await();
}
value=data[--index];
moreSpace.signalAll();
}catch(InterruptedExceptione){
e.printStackTrace();
}finally{
lock.unlock();
}
returnvalue;
}
}


寫入線程 WriteStack.java

importjava.util.Random;

{

privateStackstack;

publicWriteStack(Stackstack){
this.stack=stack;
}

@Override
publicvoidrun(){
Randomr=newRandom(System.currentTimeMillis());
for(inti=0;i<10;i++){
intvalue=r.nextInt(500);
stack.push(value);
System.out.printf("Write:push%dinstack ",value);
try{
Thread.sleep(r.nextInt(500));
}catch(InterruptedExceptione){
e.printStackTrace();
}
}
}

}

讀取線程 ReadStack.java

importjava.util.Random;

{

privateStackstack;

publicReadStack(Stackstack){
this.stack=stack;
}

@Override
publicvoidrun(){
Randomr=newRandom(System.currentTimeMillis());
for(inti=0;i<10;i++){
intvalue=stack.popup();
System.out.printf("Read:popupanelement%d ",value);
try{
Thread.sleep(r.nextInt(500));
}catch(InterruptedExceptione){
e.printStackTrace();
}
}
}
}


主測試線程 StackExample.java

publicclassStackExample{
publicstaticvoidmain(String[]args)throwsInterruptedException{
Stackstack=newStack(5);
WriteStackwriteStack=newWriteStack(stack);
ReadStackreadStack=newReadStack(stack);

ThreadwriteThread=newThread(writeStack);
ThreadreadThread=newThread(readStack);
writeThread.start();
readThread.start();
}
}

Ⅳ 如何在java中使用ConcurrentHashMap

Java中ConcurrentHashMap的實現
CHM引入了分割,並提供了HashTable支持的所有的功能。在CHM中,支持多線程對Map做讀操作,並且不需要任何的blocking。這得益於CHM將Map分割成了不同的部分,在執行更新操作時只鎖住一部分。根據默認的並發級別(concurrency level),Map被分割成16個部分,並且由不同的鎖控制。這意味著,同時最多可以有16個寫線程操作Map。試想一下,由只能一個線程進入變成同時可由16個寫線程同時進入(讀線程幾乎不受限制),性能的提升是顯而易見的。但由於一些更新操作,如put(),remove(),putAll(),clear()只鎖住操作的部分,所以在檢索操作不能保證返回的是最新的結果。
另一個重要點是在迭代遍歷CHM時,keySet返回的iterator是弱一致和fail-safe的,可能不會返回某些最近的改變,並且在遍歷過程中,如果已經遍歷的數組上的內容變化了,不會拋出的異常。
CHM默認的並發級別是16,但可以在創建CHM時通過構造函數改變。毫無疑問,並發級別代表著並發執行更新操作的數目,所以如果只有很少的線程會更新Map,那麼建議設置一個低的並發級別。另外,CHM還使用了ReentrantLock來對segments加鎖。

Ⅳ 哪本Java 面試書籍比較好

BooksThinking
in
Java
(Java
101,
must
read)
Java
Puzzlers
(適合面試官,
如果你找不到很好的java
面試題的話,
可以從這本書找些靈感,
其中很多"奇技淫巧",
小心走火入魔)
Java
Concurrency
In
practice,
對於java
伺服器開發,大並發,很適合。
Concurrent
Programming
in
Java:
Design
Principles
and
PatternsDoug
Lea語言和虛擬機方面可以參考
Inside
the
Java
2
Virtual
Machine
Inside
Java
2
Platform
Security
by
宮力.
Garbage
Collection:
Algorithms
for
Automatic
Dynamic
Memory
Management這些書的作者多數是當年Sun
Java
team
的成員。
另外Quora
上很多問題可以關注一下
What
questions
are
Java
Software
Engineers
seeing
the
most
of
on
technical
interviews?Java
(programming
language):
What
are
good
interview
questions
to
ask
JAVA
developers?作為面試官,當你的對手聲稱對Java
非常了解的時候,
可以就上述話題展開較深入的討論,
觀察其思維方式和見解。
個人更傾向的不是語言層面上的東西,畢竟術業有專攻,
讓宮力去和Doug
Lea
討論並發問題並不一定能夠過關。

Ⅵ java 中 synchronized 是什麼意思

一段synchronized的代碼被一個線程執行之前,他要先拿到執行這段代碼的許可權,在java里邊就是拿到某個同步對象的鎖(一個對象只有一把鎖); 如果這個時候同步對象的鎖被其他線程拿走了,他(這個線程)就只能等了(線程阻塞在鎖池等待隊列中)。 取到鎖後,他就開始執行同步代碼(被synchronized修飾的代碼);線程執行完同步代碼後馬上就把鎖還給同步對象,其他在鎖池中等待的某個線程就可以拿到鎖執行同步代碼了。這樣就保證了同步代碼在統一時刻只有一個線程在執行。
關於線程的同步,一般有以下解決方法:

1. 在需要同步的方法的方法簽名中加入synchronized關鍵字。

2. 使用synchronized塊對需要進行同步的代碼段進行同步。

3. 使用JDK 5中提供的java.util.concurrent.lock包中的Lock對象

Ⅶ java中屬於什麼異常

運行這段代碼的結果

Exception in thread "main" Java.util.
at java.util.AbstractList$Itr.checkForComodification(Unknown Source)
at java.util.AbstractList$Itr.next(Unknown Source)
at com.debug.Debug.main(Debug.java:28)

大家都知道for(String str : set)這句話實際上是用到了集合的iterator() 方法
在iterator的時候是產生了一個List的內部類Itr
JDK源碼
public Iterator<E> iterator() {
return new Itr();
}
在new Itr()時有一個關鍵性的操作
/**
* The modCount value that the iterator believes that the backing
* List should have. If this expectation is violated, the iterator
* has detected concurrent modification.
*/
int expectedModCount = modCount;

再回頭看一下List的remove方法
public boolean remove(Object o) {
if (o == null) {
for (int index = 0; index < size; index++)
if (elementData[index] == null) {
fastRemove(index);
return true;
}
} else {
for (int index = 0; index < size; index++)
if (o.equals(elementData[index])) {
fastRemove(index);
return true;
}
}
return false;
}

private void fastRemove(int index) {
modCount++;
int numMoved = size - index - 1;
if (numMoved > 0)
System.array(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // Let gc do its work
}

Ⅷ java concurrenthashmap和hashmap的區別

最大的區別就是ConcurrentHashMap是線程安全的,hashMap不是線程安全的。
為什麼線程安全呢:
ConcurrentHashMap代碼中可以看出,它引入了一個「分段鎖」的概念,具體可以理解為把一個大的Map拆分成N個小的HashTable,根據key.hashCode()來決定把key放到哪個HashTable中。
在ConcurrentHashMap中,就是把Map分成了N個Segment,put和get的時候,都是現根據key.hashCode()算出放到哪個Segment中:

Ⅸ Concurrent Programming in Java 有中文版嗎

你好,這本書目前沒有中文版,只有暢銷書才有可能被譯為中文,國人現在都比較浮躁,中文版的外籍書越來越少了。唉。

熱點內容
伺服器ip轉載 發布:2025-02-12 05:19:12 瀏覽:296
oraclesql插入數據 發布:2025-02-12 05:19:05 瀏覽:918
stl源碼剖析筆記 發布:2025-02-12 05:01:51 瀏覽:589
教務系統web伺服器搭建 發布:2025-02-12 05:01:17 瀏覽:98
全國dns伺服器地址大全 發布:2025-02-12 05:01:13 瀏覽:683
安卓什麼軟體能拍到月亮 發布:2025-02-12 04:59:42 瀏覽:782
手機卡忘記服務密碼怎麼辦 發布:2025-02-12 04:59:10 瀏覽:374
如何讓助理伺服器可以被遠程 發布:2025-02-12 04:47:11 瀏覽:770
存儲空間不足但 發布:2025-02-12 04:46:27 瀏覽:278
樹莓派編程板 發布:2025-02-12 04:41:45 瀏覽:909