我看到了这个:
// thread is a member of this class
synchronized( this.thread )
{
this.thread.running = false;
this.thread.notifyAll(); // Wake up anything that was .waiting() on
// the thread
this.thread = null; // kill this thread reference.
// can you do that in a synchronized block?
}
Run Code Online (Sandbox Code Playgroud)
是否可以设置thread=nullwhile仍然保持锁定?
我在一些BB代码中找到了这个金块.
下面是一个简单的java程序.它有一个名为"cnt"的计数器,它会递增,然后添加到名为"monitor"的List中."cnt"由多个线程递增,并且值被多个线程添加到"监视器".
在方法"go()"的末尾,cnt和monitor.size()应该具有相同的值,但它们不具有相同的值.monitor.size()确实有正确的值.
如果通过取消注释其中一个已注释的同步块来更改代码,并注释掉当前未注释的块,则代码会生成预期结果.此外,如果将线程计数(THREAD_COUNT)设置为1,则代码会生成预期结果.
这只能在具有多个真实核心的计算机上重现.
public class ThreadTester {
private List<Integer> monitor = new ArrayList<Integer>();
private Integer cnt = 0;
private static final int NUM_EVENTS = 2313;
private final int THREAD_COUNT = 13;
public ThreadTester() {
}
public void go() {
Runnable r = new Runnable() {
@Override
public void run() {
for (int ii=0; ii<NUM_EVENTS; ++ii) {
synchronized( monitor) {
synchronized(cnt) { // <-- is this synchronized necessary?
monitor.add(cnt);
}
// synchronized(cnt) {
// cnt++; // <-- why does moving …Run Code Online (Sandbox Code Playgroud) java concurrency multithreading synchronized synchronized-block
我想使用synchronized块作为flatMap的源码.但我需要使用此构造进行处理(方法processItem),而不仅仅是在创建内部源时.
每隔5分钟调用一次Observable(例如Observable.interval)
Observable.fromIterable(getSourceData())
.flatMapCompletable(item -> {
synchronized(LockManager.getInstance().getLockObject(item.id)){
return processItem(item)
.subscribeOn(Schedulers.io());
}
})
Run Code Online (Sandbox Code Playgroud)
我的processsItem方法如下所示:
public Completable processItem(Item item){
return mApiSource.getItemById(item.id)
.flatMap(item ->
mItemRepository.replace(item)
)
.toCompletable();
}
Run Code Online (Sandbox Code Playgroud)
两个内部方法都返回Single.
它是从服务器定期更新的方法的一部分.我需要序列化processItem方法调用(从服务器定期同步项目)和修改项目(更新,删除)的方法,这些方法是从其他项目类调用的(项目同步).
主要问题是定期更新可以重写新更新的项目.
其实我用这个解决方案:
用于更新新项目的链:
public Completable updateItem(Item item){
return Completable.fromAction(() -> {
synchronized(LockManager.getInstance().getLockObject(item.id)){
mApiSource.update(item)
.flatMap(item ->
mItemRepository.replace(item)
)
.toCompletable()
.blockingAwait();
}
})
.subscribeOn(Schedulers.io())
}
Run Code Online (Sandbox Code Playgroud)
定期更新链:
Observable.fromIterable(getSourceData())
.flatMapCompletable(item -> {
Completable.fromAction(() ->{
synchronized(LockManager.getInstance().getLockObject(item.id)){
processItem(item).blockingAwait();
}
})
.subscribeOn(Schedulers.io())
});
Run Code Online (Sandbox Code Playgroud)
我知道RxJava解决方案并不清楚.
你知道更好的解决方案吗?
synchronized synchronized-block thread-synchronization rx-java2
public class ObjectCounter {
private static long numOfInstances = 0;
public ObjectCounter(){
synchronized(this){
numOfInstances++;
}
}
**public static synchronized long getCount(){
return numOfInstances;
}**
//vs//
**public static long getCount(){
return numOfInstances;
}**
}
Run Code Online (Sandbox Code Playgroud)
如果我运行少量线程,其中一些调用静态函数getCount(),其中一些创建新实例.我希望每次调用getCount()实际数量的实例.
this"不应该意味着我不能调用,getCount()直到构造函数退出synchronized块(假设我没有在getCount()上写同步).this"代码?`
java multithreading synchronized synchronized-block java-threads
这段代码不会编译:
synchronized( obj ) {
Object a = new Object()
}
System.out.println( a.toString() );
Run Code Online (Sandbox Code Playgroud)
但我不知道为什么..我的理解是同步块总是最终被执行,所以我希望在synchronized块之后的代码能够知道任何新的声明变量.我哪里错了?
我有两个正在运行的线程调用几个方法(5或6),我在其中指定了synchronized块,并且只使用一个对象来锁定它.只有一个同步点是否有任何死锁的可能性?到目前为止,我还没有看到过这样的情况.感谢帮助.
有什么区别:
public synchronized void test(){}
Run Code Online (Sandbox Code Playgroud)
和
public void test() {
synchronized(Sample.class){}
}
Run Code Online (Sandbox Code Playgroud) public Foo getFoo(){
Foo foo = null;
synchronized(fooList){
if(fooList.size() > 0){
foo = fooList.remove(0);
}
}
return foo;
}
Run Code Online (Sandbox Code Playgroud)
由于foo是在同步块之外声明的,是否存在返回错误数据的可能性?
我需要像这样的线程安全的arraylist.
public class BookingList {
private List<Booking> bookings;
public BookingList() {
bookings = Collections.synchronizedList(new ArrayList<Booking>());
}
@Override
public void addBooking(Booking booking)
{
synchronized (bookings) {
bookings.add(booking);
}
}
@Override
public void removeBooking(Booking booking)
{
synchronized (bookings) {
bookings.remove(booking);
}
}
}
Run Code Online (Sandbox Code Playgroud)
根据java doc,当使用Collections.synchronizedList时,需要同步对列表的每次访问.我不确定我的同步块是否会这样做?
我使用的synchronized块是否相当于
...
public synchronized void addBooking(Booking booking) {
bookings.add(booking);
}
Run Code Online (Sandbox Code Playgroud)我应该像这样使用ReentrantLock吗?
private Lock lock = new ReentrantLock();
public void addBooking(Booking booking) {
try {
lock.lock;
bookings.add(booking);
} finally {
lock.release();
}
}
Run Code Online (Sandbox Code Playgroud)以下是在讨论开放调用时来自实践本书中java并发的代码片段.我没有得到的是setLocation方法的声明方式,它已经被同步并再次在同一个方法中调用synchronized(this)块,为什么呢?是类型错误吗?synchronized方法已经锁定了这个方法然后为什么再次对同一个对象?
@ThreadSafe
class Taxi {
@GuardedBy("this") private Point location, destination;
private final Dispatcher dispatcher;
...
public synchronized Point getLocation() {
return location;
}
public synchronized void setLocation(Point location) {
boolean reachedDestination;
synchronized (this) {
this.location = location;
reachedDestination = location.equals(destination);
}
if (reachedDestination)
dispatcher.notifyAvailable(this);
}
}
Run Code Online (Sandbox Code Playgroud) 鉴于以下输出:
Path path1 = Paths.get("/Users/someone/foo");
Path path2 = Paths.get("/Users/someone/foo");
System.out.println(path1.toString() == path2.toString()); // outputs false
System.out.println(path1.toString().equals(path2.toString())); // outputs true
Run Code Online (Sandbox Code Playgroud)
给定以下两个线程,两个线程是否可以同时在关键部分运行?
// Thread 1
synchronized (path1.toString()) {
// Critical section
}
// Thread 2
synchronized (path2.toString()) {
// Critical section
}
Run Code Online (Sandbox Code Playgroud) java multithreading synchronization synchronized synchronized-block
我有一个打印计数器的同步方法,我有 4 个线程,所以我期望计数器的最终值为 400000,因为我的计数器是一个静态变量。
但每次我运行代码时,它都会给我不同的计数器值。
以下是我的代码:
class MyThread implements Runnable{
private static int counter=1;
@Override
public void run() {
try {
this.syncMethod();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public synchronized void syncMethod() throws InterruptedException{
for(int i=0;i<100000;i++){
System.out.println(Thread.currentThread().getName()+" : "+counter++);
}
}
}
public class MyController {
public static void main(String[] args) throws InterruptedException {
Runnable r1=new MyThread();
Runnable r2=new MyThread();
Runnable r3=new MyThread();
Runnable r4=new MyThread();
Thread t1;
Thread t2;
Thread t3;
Thread t4;
t1=new Thread(r1,"Thread 1");
t2=new …Run Code Online (Sandbox Code Playgroud) 在这个简单的例子中,我有两个synchronized (theLock)由不同的线程访问
public class Main {
public static void main(String[] args) throws InterruptedException {
System.out.println("start");
final Object theLock = new Object();
synchronized (theLock) {
System.out.println("main thread id : " + Thread.currentThread().getId());
new Thread(() -> {
System.out.println("new thread id : " + Thread.currentThread().getId() + ". Inside thread");
// before entering this section new thread should be blocked as `theLock` is already acquired
synchronized (theLock) {
System.out.println("inside synchronized");
theLock.notify();
}
}).start();
theLock.wait();
}
System.out.println("end");
}
}
Run Code Online (Sandbox Code Playgroud)
为什么新创建的线程可以访问synchronized (theLock)里面的部分?据我所知, …