当前位置:首页 » 编程语言 » 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 有中文版吗

你好,这本书目前没有中文版,只有畅销书才有可能被译为中文,国人现在都比较浮躁,中文版的外籍书越来越少了。唉。

热点内容
战舰少女r红茶脚本 发布:2025-02-12 04:05:05 浏览:465
峰火战国服务器什么时候开 发布:2025-02-12 03:56:31 浏览:175
电脑配置慢怎么解压 发布:2025-02-12 03:52:18 浏览:716
androidsdk功能 发布:2025-02-12 03:43:07 浏览:87
阿里云服务器可以访问外网吗 发布:2025-02-12 03:42:20 浏览:880
脚本的生命周期顺序 发布:2025-02-12 03:37:28 浏览:369
素数加密 发布:2025-02-12 03:37:27 浏览:803
ar源码 发布:2025-02-12 03:32:04 浏览:656
阅图文件夹 发布:2025-02-12 03:30:22 浏览:762
旧手机存储资料 发布:2025-02-12 03:29:42 浏览:472