活动地址:CSDN21天学习挑战赛
1、设计4个线程对象
题目:设计4个线程对象,两个线程执行减操作,两个线程执行加操作。
代码如下:
//执行加运算的线程
class Add implements Runnable{
private int sum = 0;
@Override
public void run() {
for(int i=0; i<10; i++){
sum += i;
}
System.out.println("相加的结果: " + this.sum);
}
}
//执行减运算的线程
class Subtraction implements Runnable{
private int sum = 100;
@Override
public void run() {
for(int i=10; i>0; i--){
sum -= i;
}
System.out.println("相减后的结果: " + this.sum);
}
}
//主函数
public class Demo1{
public static void main(String[] args) {
Add a = new Add();
Thread t1 = new Thread(a);
Thread t2 = new Thread(a);
t1.start();
t2.start();
Subtraction s = new Subtraction();
Thread t3 = new Thread(s);
Thread t4 = new Thread(s);
t3.start();
t4.start();
}
}
运行结果:
相加的结果: 45
相加的结果: 90
相减后的结果: 45
相减后的结果: -10
2、设计一个生产电脑和搬运电脑类
题目:设计一个生产电脑和搬运电脑类,要求生产出一台电脑就搬走一台电脑,如果没有新的电脑生产出来,则搬运工要等待新电脑产出;如果生产出的电脑没有搬走,则要等待电脑搬走之后再生产,并统计出生产的电脑数量。
代码如下:
public class Demo2 {
public static void main(String[] args) throws Exception {
Resource res = new Resource();
Producer st = new Producer(res);
Consumer at = new Consumer(res);
new Thread(at).start();
new Thread(at).start();
new Thread(st).start();
new Thread(st).start();
}
}
class Producer implements Runnable {
private Resource resource;
public Producer(Resource resource) {
this.resource = resource;
}
@Override
public void run() {
for (int i = 0; i < 50; i++) {
try {
this.resource.make();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Consumer implements Runnable {
private Resource resource;
public Consumer(Resource resource) {
this.resource = resource;
}
@Override
public void run() {
for (int i = 0; i < 50; i++) {
try {
this.resource.get();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Resource {
private Computer computer;
public synchronized void make() throws InterruptedException {
while (computer != null) {//已经生产过了
wait();
}
Thread.sleep(100);
this.computer = new Computer("DELL", 1.1);
System.out.println("【生产】" + this.computer);
notifyAll();
}
public synchronized void get() throws InterruptedException {
while (computer == null) {//已经生产过了
wait();
}
Thread.sleep(10);
System.out.println("【搬运】" + this.computer);
this.computer = null;
notifyAll();
}
}
class Computer {
private static int count;//表示生产的个数
private String name;
private double price;
public Computer(String name, double price) {
this.name = name;
this.price = price;
this.count++;
}
@Override
public String toString() {
return "【第" + count + "台电脑】电脑名字:" + this.name + "价值、" + this.price;
}
}
运行结果:
【生产】【第2台电脑】电脑名字:DELL价值、1.1
【搬运】【第2台电脑】电脑名字:DELL价值、1.1
【生产】【第3台电脑】电脑名字:DELL价值、1.1
【搬运】【第3台电脑】电脑名字:DELL价值、1.1
【生产】【第4台电脑】电脑名字:DELL价值、1.1
【搬运】【第4台电脑】电脑名字:DELL价值、1.1
【生产】【第5台电脑】电脑名字:DELL价值、1.1
【搬运】【第5台电脑】电脑名字:DELL价值、1.1
········
········
【生产】【第98台电脑】电脑名字:DELL价值、1.1
【搬运】【第98台电脑】电脑名字:DELL价值、1.1
【生产】【第99台电脑】电脑名字:DELL价值、1.1
【搬运】【第99台电脑】电脑名字:DELL价值、1.1
【生产】【第100台电脑】电脑名字:DELL价值、1.1
【搬运】【第100台电脑】电脑名字:DELL价值、1.1