算法
字符串翻转函数
strrev()
函数用于char字符串数组,reverse()
函数用于string类型的字符串。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| #include <iostream> #include <cstring> using namespace std; int main() { char s[]="hello"; strrev(s); cout<<s<<endl; return 0; }
#include <iostream> #include <string> #include <algorithm> using namespace std; int main() { string s = "hello"; reverse(s.begin(),s.end()); cout<<s<<endl; return 0; }
|
auto遍历
1 2 3
| vector<int> res; for(auto it : res) cout << it;
|
java
CopyOnWriteArrayList
CopyOnWriteArrayList
是线程安全的
1
| CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<Stirng>();
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| package test;
import java.util.concurrent.CopyOnWriteArrayList;
public class TestCopyOnWriteArrayList { public static void main(String[] args) { CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<String>(); for (int i = 0; i < 10000; i++) { new Thread(() -> { list.add(Thread.currentThread().getName()); }).start(); } try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(list.size()); } }
|
死锁
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
| package test;
public class DeadLock {
public static void main(String[] args) { Makeup g1 = new Makeup(0, "小明"); Makeup g2 = new Makeup(1 , "小红");
g1.start(); g2.start(); } }
class Lipstick {
}
class Mirror {
}
class Makeup extends Thread { static Lipstick lipstick = new Lipstick(); static Mirror mirror = new Mirror(); int choice; String girlName;
public Makeup(int choice, String girlName) { this.choice = choice; this.girlName = girlName; }
@Override public void run() { try { makeup(); } catch (InterruptedException e) { e.printStackTrace(); } }
private void makeup() throws InterruptedException { if(choice == 0) { synchronized (lipstick) { System.out.println(this.girlName + "获得口红锁"); Thread.sleep(1000); } // 分开锁 synchronized (mirror) { System.out.println(this.girlName + "获得镜子锁"); } } else { synchronized (mirror) { System.out.println(this.girlName + "获得镜子锁"); Thread.sleep(2000); } synchronized (lipstick) { System.out.println(this.girlName + "获得口红锁"); } } } }
|