水浅

  • Home

  • Tags14

  • Categories10

  • Search

CountDownLatch 和 CyclicBarrier

Posted on 2021-02-17 | Edited on 2021-02-24 | In java系列
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
public class CountDownLatchTest {

public static void main(String[] args) throws InterruptedException {
CountDownLatch latch = new CountDownLatch(4);
for(int i = 0;i < latch.getCount();i++){
new Thread(new MyThread(latch),"player" + i).start();
}
System.out.println("等待 所所有玩家 准备好");
latch.await();
System.out.println("开始游戏");
}


private static class MyThread implements Runnable{
private CountDownLatch latch;

public MyThread(CountDownLatch latch){
this.latch = latch;
}
@SneakyThrows
@Override
public void run() {

Random rand = null;
try {
rand = new Random();
int randomNum = rand.nextInt((3000 - 1000) +1 ) + 1000;
Thread.sleep(randomNum);
System.out.println(Thread.currentThread().getName() + "已经准备好 " + "所使用的时间是:" + randomNum );
latch.countDown();
} catch (Exception e) {
e.printStackTrace();
}

}
}
}
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
public class CyclicBarrierTest {
public static void main(String[] args) {
CyclicBarrier barrier = new CyclicBarrier(3);
for(int i = 0; i < barrier.getParties(); i++){
new Thread(new MyRunnable(barrier), "队友"+i).start();
}
System.out.println("main function is finished.");
}


private static class MyRunnable implements Runnable{
private CyclicBarrier barrier;

public MyRunnable(CyclicBarrier barrier){
this.barrier = barrier;
}

@Override
public void run() {
for(int i = 0; i < 3; i++) {
try {
Random rand = new Random();
int randomNum = rand.nextInt((3000 - 1000) + 1) + 1000;//产生1000到3000之间的随机整数
Thread.sleep(randomNum);
System.out.println(Thread.currentThread().getName() + ", 通过了第"+i+"个障碍物, 使用了 "+((double)randomNum/1000)+"s");
this.barrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}
}
}
}

总结:CountDownLatch和CyclicBarrier都有让多个线程等待同步然后再开始下一步动作的意思,但是CountDownLatch的下一步的动作实施者是主线程,具有不可重复性;而CyclicBarrier的下一步动作实施者还是“其他线程”本身,具有往复多次实施动作的特点。

String StringBuilder StringBuffer

Posted on 2021-02-16 | In 面试
String StringBuffer StringBuilder
String的值是不可变的,这就导致每次对String的操作都会生成新的String对象,不仅效率低下,而且浪费大量优先的内存空间 StringBuffer是可变类,和线程安全的字符串操作类,任何对它指向的字符串的操作都不会产生新的对象。每个StringBuffer对象都有一定的缓冲区容量,当字符串大小没有超过容量时,不会分配新的容量,当字符串大小超过容量时,会自动增加容量 可变类,速度更快
线程安全 线程不安全

正则表达式

Posted on 2021-02-16 | Edited on 2021-02-24 | In java系列
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* @author devin
* @version 1.0.2
* @date 2021-02-16 23:23
*/
public class Zhenze {
// 待匹配字符串

public static void main(String[] args) {
String str = "湖北省武汉市1573rr4562";
Pattern p = Pattern.compile("[1-9]+");
Matcher m = p.matcher(str);
while(m.find()){
System.out.println(m.group());
}
}

}

深拷贝 浅拷贝解析

Posted on 2021-02-15 | Edited on 2021-03-01 | In java系列

python 爬取图片

Posted on 2021-02-14

思路分析:

​ requests 获得需要爬取的网页

​ 将爬取的网页数据做成BeautifulSoup

​ 应用soup 的API 找到需要的标签属性

通过标签属性获得二进制字节保存

1
2
3
4
5
6
7
8
9
10
11
12
13
import requests
from bs4 import BeautifulSoup

data = requests.get("url")
data.encoding = data.apparent_encoding

soup = BeautifulSoup(data.text)
link = soup.select_one("#container > div > div > div:nth-child(3) > div.list_con_box > div.zt_con_img > dl > dd > ul > li:nth-child(1) > a > img")['src']
f = open("D://a.jpg","wb")

pic_data = requests.get(link)
f.write(pic_data.content)
f.close()

手写数字识别

Posted on 2021-02-14
  • 具体参考
    https://www.cnblogs.com/endlesscoding/p/9901539.html
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
from sklearn.datasets import fetch_mldata
from sklearn import datasets
import numpy as np
## 样本可能下载超时
mnist = fetch_mldata('mnist-original', data_home = './datasets/')
mnist



X, y = mnist['data'], mnist['target']
print(X.shape)
print(y.shape)



%matplotlib inline
import matplotlib
import matplotlib.pyplot as plt

# 第一个样本
some_digit = X[1]
some_digit_image = some_digit.reshape(28,28)

plt.imshow(some_digit_image, cmap=matplotlib.cm.binary, interpolation="nearest")
plt.axis('off')
plt.show()


# EXTRA
def plot_digits(instances, images_per_row=10, **options):
size = 28
images_per_row = min(len(instances), images_per_row)
images = [instance.reshape(size,size) for instance in instances]
n_rows = (len(instances) - 1) // images_per_row + 1
row_images = []
n_empty = n_rows * images_per_row - len(instances)
images.append(np.zeros((size, size * n_empty)))
for row in range(n_rows):
rimages = images[row * images_per_row : (row + 1) * images_per_row]
row_images.append(np.concatenate(rimages, axis=1))
image = np.concatenate(row_images, axis=0)
plt.imshow(image, cmap = matplotlib.cm.binary, **options)
plt.axis("off")

plt.figure(figsize=(9,9))
example_images = np.r_[X[:12000:600], X[13000:30600:600], X[30600:60000:590]]
plot_digits(example_images, images_per_row=10)
# save_fig("more_digits_plot")
plt.show()


X_train, X_test, y_train, y_test = X[:60000],X[60000:],y[:60000],y[60000:]
# 打乱标签
import numpy as np

shuffle_index = np.random.permutation(60000)
X_train, y_train = X_train[shuffle_index],y_train[shuffle_index]


# 训练一个二分器
# 这是一个逻辑数组,5:True, 非5:False
y_train_5 = (y_train == 5)
y_test_5 = (y_test == 5)


from sklearn.linear_model import SGDClassifier

sgd_clf = SGDClassifier(random_state = 32)
sgd_clf.fit(X_train, y_train_5)


SGDClassifier(alpha=0.0001, average=False, class_weight=None,
early_stopping=False, epsilon=0.1, eta0=0.0, fit_intercept=True,
l1_ratio=0.15, learning_rate='optimal', loss='hinge', max_iter=None,
n_iter=None, n_iter_no_change=5, n_jobs=None, penalty='l2',
power_t=0.5, random_state=32, shuffle=True, tol=None,
validation_fraction=0.1, verbose=0, warm_start=False)
sgd_clf.predict([some_digit])
array([ True])

sgd_clf = SGDClassifier(random_state = 42)
sgd_clf.fit(X_train, y_train_5)
sgd_clf.predict([some_digit])


from sklearn.model_selection import StratifiedKFold
from sklearn.base import clone


# 使用交叉验证测量准确性
skfolds = StratifiedKFold(n_splits = 3, random_state = 42)
clone_clf = clone(sgd_clf)
for train_index, test_index in skfolds.split(X_train, y_train_5):
X_train_folds = X_train[train_index]
y_train_folds = (y_train_5[train_index])
X_test_fold = X_train[test_index]
y_test_fold = (y_train_5[test_index])
clone_clf.fit(X_train_folds, y_train_folds)
y_pred = clone_clf.predict(X_test_fold)
n_correct = sum(y_pred == y_test_fold)
print(n_correct / len(y_pred))




from sklearn.model_selection import cross_val_score
cross_val_score(sgd_clf, X_train, y_train_5, cv = 3, scoring = "accuracy")
from sklearn.base import BaseEstimator
# 这个模型的预测的策略就是将所有的数据都认为是'非5'
class Never5Classifier(BaseEstimator):
def fit(self,X,y=None):
pass
def predict(self,X):
return np.zeros((len(X),1), dtype=bool)

never_5_clf = Never5Classifier()
cross_val_score(never_5_clf, X_train, y_train_5, cv = 3, scoring = "accuracy")
from sklearn.model_selection import cross_val_predict

y_train_pred = cross_val_predict(sgd_clf, X_train, y_train_5, cv = 3)

单例模式

Posted on 2021-02-14
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
/**
*
* @author devin
* @date 2021-01-08 11:12
* @version 1.0.2
*/
public class SingleTest {

private static volatile SingleTest instance;

private SingleTest(){
System.out.println("create method");
}

//在这里加同步太重
public static SingleTest getInstance(){
if(instance == null){
synchronized (SingleTest.class){
if(instance == null){
return instance = new SingleTest();
}
}
}

return instance;

}

public static void main(String[] args) {
for(int i = 0;i < 1000;i++){
new Thread(){
@Override
public void run() {
SingleTest.getInstance();
}
}.start();
}

}
}

jvm参数调试demo

Posted on 2021-02-13
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
/**
* @author devin
* @version 1.0.2
* @date 2021-01-13 20:48
*/
public class Demo2 {
private static final int _512KB = 512 * 1024;
private static final int _1MB = 1024 * 1024;
private static final int _6MB = 6 * 1024 * 1024;
private static final int _7MB = 7 * 1024 * 1024;
private static final int _8MB = 8 * 1024 * 1024;

// -Xms20M -Xmx20M -Xmn10M -XX:+UseSerialGC -XX:+PrintGCDetails -verbose:gc

public static void main(String[] args) throws InterruptedException {

BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(3);
queue.add(2);
queue.add(3);
queue.add(5);
queue.put(3);
System.out.println(queue.take());
}

}

wait 释放锁

Posted on 2021-02-13
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
66
67
class ThreadB2 extends Thread {

/**
* 线程 BBB 持有对象锁 this,即当前对象 threadB2
*/
@Override
public void run() {
synchronized (this) {
System.out.println(Thread.currentThread().getName() + " beg "
+ System.currentTimeMillis());
System.out.println("B2 ing");
System.out.println(Thread.currentThread().getName() + " end "
+ System.currentTimeMillis());
}
}
}

class ThreadA2 extends Thread {

private ThreadB2 threadB2;

public ThreadA2(ThreadB2 threadB2) {
this.threadB2 = threadB2;
}

/**
* 线程 AAA 持有对象锁 threadB2
*/

@Override
public void run() {
//B2 被锁住
synchronized (threadB2) {
System.out.println(Thread.currentThread().getName() + " beg "
+ System.currentTimeMillis());
try {
System.out.println("wait之前:" + threadB2.isAlive());
threadB2.wait();
System.out.println("wait之后:" + threadB2.isAlive());
} catch (InterruptedException e) {
e.printStackTrace();
}
// try {
// Thread.sleep(2000);
// } catch (InterruptedException e) {
// }
System.out.println(Thread.currentThread().getName() + " end "
+ System.currentTimeMillis());
}
}
}

class Run2 {

public static void main(String[] args) {
ThreadB2 threadB2 = new ThreadB2();
threadB2.setName("B2");
ThreadA2 threadA2 = new ThreadA2(threadB2);
threadA2.setName("A2");



threadA2.start();
threadB2.start();
}

}

对象锁

Posted on 2021-02-13
1234
Author

Author

40 posts
10 categories
14 tags
GitHub 简书
Links
  • csdn
  • github
© 2021 认识世界 认识你自己