Java 多线程和线程同步

2020-04-03  本文已影响0人  大佬的上半生

进程和线程

多线程的使⽤

Thread thread = new Thread() {
@Override
public void run() {
System.out.println("Thread started!");
 }
};
thread.start();

Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("Thread with Runnable started!");
 }
};
Thread thread = new Thread(runnable);
thread.start();
ThreadFactory factory = new ThreadFactory() {
int count = 0;
@Override
public Thread newThread(Runnable r) {
count ++;
return new Thread(r, "Thread-" + count);
 }
};
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "
started!");
 }
};
Thread thread = factory.newThread(runnable);
thread.start();
Thread thread1 = factory.newThread(runnable);
thread1.start();
Executor 和线程池
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("Thread with Runnable started!");
 }
};
Executor executor = Executors.newCachedThreadPool();
executor.execute(runnable);
executor.execute(runnable);
executor.execute(runnable);
ExecutorService executor = Executors.newFixedThreadPool(20);
for (Bitmap bitmap : bitmaps) {
executor.execute(bitmapProcessor(bitmap));
}
executor.shutdown();
Callable<String> callable = new Callable<String>() {
@Override
public String call() {
try {
Thread.sleep(1500);
 } catch (InterruptedException e) {
e.printStackTrace();
 }
return "Done!";
 }
};
ExecutorService executor = Executors.newCachedThreadPool();
Future<String> future = executor.submit(callable);
try {
String result = future.get();
System.out.println("result: " + result);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}

线程同步与线程安全

synchronized
private synchronized void count(int newValue) {
x = newValue; y = newValue;
if (x != y) {
System.out.println("x: " + x + ", y:" + y);
 }
}
private void count(int newValue) {
synchronized (this) {
x = newValue; y = newValue;
if (x != y) {
System.out.println("x: " + x + ", y:" + y);
 }
 }
}

synchronized (monitor1) {
synchronized (monitor2) {
name = x + "-" + y;
 }
}
Lock lock = new ReentrantLock();
...
lock.lock();
try {
x++;
} finally {
lock.unlock();
}

finally 的作⽤:保证在⽅法提前结束或出现 Exception 的时候,依然能正常释放锁
⼀般并不会只是使⽤ Lock ,⽽是会使⽤更复杂的锁,例如 ReadWriteLock :

ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
Lock readLock = lock.readLock();
Lock writeLock = lock.writeLock();
private int x = 0;
private void count() {
writeLock.lock();
try {
x++;
 } finally {
writeLock.unlock();
 }
}
private void print(int time) {
readLock.lock();
try {
for (int i = 0; i < time; i++) {
System.out.print(x + " ");
 }
System.out.println();
 } finally {
readLock.unlock();
 }
}
上一篇 下一篇

猜你喜欢

热点阅读