Cirry's Blog

多线程综合案例

2019-10-08
技术
java
最后更新:2024-03-22
2分钟
357字

多线程实现一边加一遍减

1
package cn.cccc.demo;
2
class AddThread implements Runnable{
3
private Resource res;
4
public AddThread(Resource res) {
5
this.res = res;
6
// TODO Auto-generated constructor stub
7
}
8
@Override
9
public void run() {
10
// TODO Auto-generated method stub
11
for(int x= 0; x < 50 ; x++){
12
try {
13
this.res.add();
14
} catch (Exception e) {
15
// TODO Auto-generated catch block
61 collapsed lines
16
e.printStackTrace();
17
}
18
}
19
20
}
21
}
22
class SubThread implements Runnable{
23
private Resource res;
24
public SubThread(Resource res) {
25
this.res = res;
26
// TODO Auto-generated constructor stub
27
}
28
@Override
29
public void run() {
30
// TODO Auto-generated method stub
31
for(int x= 0; x < 50 ; x++){
32
try {
33
this.res.sub();
34
} catch (Exception e) {
35
// TODO Auto-generated catch block
36
e.printStackTrace();
37
}
38
}
39
40
}
41
}
42
class Resource { // 定义一个操作的资源
43
private int num ; // 这个是要进行加减的元数据
44
private boolean flag = false; // 加减的切换
45
46
public synchronized void add() throws Exception{ // 加法
47
if(this.flag == false){ //现在需要执行的减法操作,加法操作等待
48
super.wait();
49
}
50
51
Thread.sleep(100);
52
this.num++;
53
System.out.println("[加法操作 - ]" + Thread.currentThread().getName() + "] num = " + this.num);
54
this.flag = false;
55
super.notifyAll();
56
}
57
public synchronized void sub() throws Exception{
58
if(this.flag == true){
59
super.wait();
60
}
61
Thread.sleep(200);
62
this.num --;
63
System.out.println("[减法操作 - ]" + Thread.currentThread().getName() + "] num = " + this.num);
64
this.flag = true;
65
super.notifyAll();
66
}
67
}
68
public class ThreadDemo {
69
public static void main(String[] args) throws Exception{
70
Resource res =new Resource();
71
AddThread at = new AddThread(res);
72
SubThread st = new SubThread(res);
73
new Thread(at, "加法线程").start();
74
new Thread(st, "减法线程").start();
75
}
76
}

设计一个生产电脑和搬运电脑类,要求生产出一台电脑就搬走一台,如果没有新电脑生产则不搬,如果电脑没被搬走则不生产,并统计出生产的电脑数量。

本文标题:多线程综合案例
文章作者:Cirry
发布时间:2019-10-08
版权声明:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
感谢大佬送来的咖啡☕
alipayQRCode
wechatQRCode