51,407
社区成员
发帖
与我相关
我的任务
分享
/*
*run:
*test.ThreadT@ca0b6写入counts值:1,读出counts值:1
*test.ThreadT@14318bb写入counts值:0,读出counts值:1
*test.ThreadT@ca0b6写入counts值:2,读出counts值:3
*test.ThreadT@14318bb写入counts值:3,读出counts值:3
*test.ThreadT@14318bb写入counts值:5,读出counts值:5
*test.ThreadT@ca0b6写入counts值:4,读出counts值:5
*test.ThreadT@ca0b6写入counts值:7,读出counts值:7
*test.ThreadT@14318bb写入counts值:6,读出counts值:7
*test.ThreadT@ca0b6写入counts值:8,读出counts值:9
*test.ThreadT@14318bb写入counts值:9,读出counts值:9
*test.ThreadT@14318bb写入counts值:11,读出counts值:11
*test.ThreadT@ca0b6写入counts值:10,读出counts值:11
*test.ThreadT@14318bb写入counts值:12,读出counts值:13
*test.ThreadT@ca0b6写入counts值:13,读出counts值:13
*test.ThreadT@ca0b6写入counts值:15,读出counts值:15
*test.ThreadT@14318bb写入counts值:14,读出counts值:15
*test.ThreadT@ca0b6写入counts值:17,读出counts值:17
*test.ThreadT@14318bb写入counts值:16,读出counts值:17
*test.ThreadT@14318bb写入counts值:19,读出counts值:19
*test.ThreadT@ca0b6写入counts值:18,读出counts值:19
*test.ThreadT@ca0b6写入counts值:21,读出counts值:21
*test.ThreadT@14318bb写入counts值:20,读出counts值:21
*成功生成(总时间:8 秒)
*/
class ThreadT implements Runnable {
int sum = 0;
static int counts = 0;
static String count = "";
public void run() {
while (true) {
/*synchronized (this)*/ {//去掉注释就可以保证读写时值是一致的了
if (sum++ <= 10) {
count = "" + (counts++);//设置值
String s = this.toString() + "写入counts值:" + count;
try {
Thread.sleep(System.currentTimeMillis() % 10 * 100); //等待1s
} catch (InterruptedException ie) {
}
System.out.println(s + ",读出counts值:" + count);
} else {
break;
}
}
try {
Thread.sleep(0);
} catch (InterruptedException w) {
}
}
}
}
public class Main {
public static void main(String[] args) {
Thread t1 = new Thread(new ThreadT());
Thread t2 = new Thread(new ThreadT());
t1.start();
t2.start();
}
}