线程锁,解决并发请求
来源:互联网 发布:工作任务分配软件 编辑:程序博客网 时间:2024/05/09 02:41
(1)
package com.example.multidownload;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import android.os.Handler;
public class WriteThread extends Thread {
private String fileName;
private int startPosition;
private boolean state=true;
private int times;
private Handler handler;
public WriteThread(String fileName,int startPosition,Handler handler) {
super();
this.fileName=fileName;
this.startPosition=startPosition;
this.handler=handler;
}
@Override
public void run() {
super.run();
try {
RandomAccessFile randomAccessFile = new RandomAccessFile(fileName, "rwd");
randomAccessFile.seek(startPosition);
while (times<100) {
if(!state)
{
//java.lang.IllegalMonitorStateException: object not locked by thread before wait()
//即this.wait();周围也要加锁,不然会报上面的错
synchronized (this) {
System.out.println(WriteThread.this.getName()+"线程等待中........"+times);
handler.sendEmptyMessage(0);
this.wait();
}
}
System.out.println(WriteThread.this.getName()+"线程执行中........"+times);
randomAccessFile.writeChars("hello:"+WriteThread.this.getName()+"="+times+"\r\n");
times++;
Thread.sleep(100);
}
handler.sendEmptyMessage(1);
randomAccessFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void pauseWrite()
{
this.state=false;
}
public void resumeWrite()
{
this.state=true;
//java.lang.IllegalMonitorStateException: object not locked by thread before notifyAll()
//即this.notifyAll();外围也要加同步锁,不然会报上面的错
synchronized (this) {
this.notifyAll();
}
}
}
(2)
public class testThread {
/**
* @param 主/子线程同步,互斥打印(轮流打印10次,重复5变).............
*/
public static void main(String[] args) {
final Print print = new Print();
new Thread() {
public void run() {
for (int i = 0; i < 5; i++) {
print.printInSubThread(i);
}
};
}.start();
//主线程运行的代码放在子线程后,不然打印了了一变就成睡眠状态了,后面的代码就运行不了
for (int i = 0; i < 5; i++) {
print.printInMainThread(i);
}
}
/////////////////////打印/////////////////////////
public static class Print {
private boolean isPrintMainThread = true;
public synchronized void printInMainThread(int rowNums) {
while (!isPrintMainThread) {
// 子线程在打印,等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int i = 0; i < 10; i++) {
System.out.println("printInMainThread" + i + "/" + rowNums);
}
isPrintMainThread = false;
this.notify();
}
public synchronized void printInSubThread(int rowNums) {
while (isPrintMainThread) {
// 主线程在打印,等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int i = 0; i < 10; i++) {
System.out.println("printInSubThread:" + i + "/" + rowNums);
}
isPrintMainThread = true;
this.notify();
}
}
}
(3)
如何避免多个线程同时下载同一张图片(防止并发,要同步)?
final ReentrantLock reentrantLock = new ReentrantLock();
for (int i = 0; i < 10; i++) {
final int j=i;
new Thread(){
public void run() {
reentrantLock.lock();
System.out.println("hello:start:"+j);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("hello:end:"+j);
reentrantLock.unlock();
};
}.start();
}
不同步(这样就并发了,各做各的事).....................
final ReentrantLock reentrantLock = new ReentrantLock();
for (int i = 0; i < 10; i++) {
final int j=i;
new Thread(){
public void run() {
//reentrantLock.lock();
System.out.println("hello:start:"+j);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("hello:end:"+j);
//reentrantLock.unlock();
};
}.start();
}
(4)
如何避免多个线程同时调用一个方法,导致数据混乱(防止并发,要同步)?
public class testSyn {
/**
* @param args
*/
public static void main(String[] args) {
new Thread(){
public void run() {
while (true) {
go("WUXIFU");
}
};
}.start();
new Thread(){
public void run() {
while (true) {
go("wuyaoping");
}
};
}.start();
}
private static /*synchronized*/void go(String s) {
for (int i = 0; i < s.length(); i++) {
System.out.print(s.charAt(i));
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println();
}
}
结果数据混乱(没有在方法里加synchronized):
在方法里加synchronized
public class testSyn {
/**
* @param args
*/
public static void main(String[] args) {
new Thread(){
public void run() {
while (true) {
go("WUXIFU");
}
};
}.start();
new Thread(){
public void run() {
while (true) {
go("wuyaoping");
}
};
}.start();
}
private static synchronized void go(String s) {
for (int i = 0; i < s.length(); i++) {
System.out.print(s.charAt(i));
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println();
}
}
结果正常:
(5)如何避免多线程请求同一个接口,只发送一次请求(只请求一次该接口)
package com.example.administrator.myapplication;import android.util.Log;import org.junit.Test;import java.lang.CloneNotSupportedException;import java.lang.Object;import java.lang.Override;import java.lang.System;import java.util.concurrent.locks.ReentrantLock;import static org.junit.Assert.*;/** * To work on unit tests, switch the Test Artifact in the Build Variants view. */public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); test(); test002(); } private void test() { final ReentrantLock reentrantLock = new ReentrantLock(); for (int i = 0; i < 10; i++) { final int position = i; new Thread(){ @Override public void run() { super.run(); final int position2=position; // ReentrantLock reentrantLock2 = new ReentrantLock(); new Person(reentrantLock,position).sayHello(new Ihello() { public void goodBye() { System.out.println("成功了" + position2); } }); } }.start(); } } private void test002() { final ReentrantLock reentrantLock = new ReentrantLock(); final Person person = new Person(reentrantLock); for (int i = 10; i < 20; i++) { final int position = i; new Thread(){ @Override public void run() { super.run(); final int position2=position; person.sayHello(new Ihello() { public void goodBye() { System.out.println("成功了" + position2); } },position2); } }.start(); } } public interface Ihello { public void goodBye(); } public class Person { private int position; ReentrantLock reentrantLock; public Person(ReentrantLock reentrantLock, int position) { this.reentrantLock = reentrantLock; this.position = position; } public Person(ReentrantLock reentrantLock) { this.reentrantLock = reentrantLock; } public void sayHello(Ihello ihello) { reentrantLock.lock(); System.out.println("start" + position); ihello.goodBye(); System.out.println("end" + position); try { //TODO 所有在等待的同样任务将全部取消 reentrantLock.lockInterruptibly(); } catch (InterruptedException e) { e.printStackTrace(); } reentrantLock.unlock(); System.out.println("结尾" + position); } public void sayHello(Ihello ihello,int position) { reentrantLock.lock(); System.out.println("start" + position); ihello.goodBye(); System.out.println("end" + position); try { //TODO 所有在等待的同样任务将全部取消 reentrantLock.lockInterruptibly(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("结尾" + position); reentrantLock.unlock(); } }}
返回结果:
java 并发
- 线程锁,解决并发请求
- Redis和请求队列解决高并发
- Socket通讯解决并发采用线程池
- http并发,操作系统如何识别对应的进程,线程请求
- java模拟并发请求测试方法是否线程安全
- Java线程并发干扰问题及解决方式(锁对象)
- 并发请求
- IIS处理并发请求时出现的问题及解决
- 大数据高并发系统架构解决千万上亿请求
- IIS处理并发请求时出现的问题及解决
- 线程、线程池、并发、同步、异步、锁
- java之多线程解决TCP服务端并发上传
- Volatile真的能解决线程并发吗?
- 使用synchronized关键字来解决并发线程互斥
- javaWeb 使用线程池+队列解决"订单并发"问题
- Java 线程和进程,并发解决之synchronized
- Orleans解决并发之痛(一):单线程
- 线程并发
- SQL 2005导入EXCEL
- LINUX下的常用指令汇总
- 等概率随机抽样问题 || 蓄水池抽样算法
- 幸运数 算法比赛
- oracle update语句卡死现象(select等正常) 解决方案
- 线程锁,解决并发请求
- OpenCV学习笔记(2):Mat矩阵的初始化
- ios+oc面试题
- NPAPI开发的DLL火狐正常加载而谷歌不能加载的解决办法
- ERROR [IM002] [Microsoft][ODBC 驱动程序管理器] 未发现数据源名称并且未指定默认驱动程序
- sqlserver带四种判断的手动存储过程分页分页
- android 下 Error format not a string literal and no format arguments 解决方案
- 判断一个字符串是否为空
- Java面试题(选择题)