java作业,在线等挺急的~ 如图 20
展开全部
两个例子两个包demo1、demo2。需求中没有说明交替或顺序执行,本例纯属娱乐,期待你更难一些的题目
需求1:
package demo1;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* 需求中知识要求并发,所以没有加入顺序执行的处理
*
* @author remind
*
*/
public class Function {
/**
* 打印100次A
*/
public synchronized void task1() {
for (int i = 0; i < 100; i++) {
System.out.print("a");
}
System.out.println();
}
/**
* 打印100次B
*/
public synchronized void task2() {
for (int i = 0; i < 100; i++) {
System.out.print("b");
}
System.out.println();
}
/**
* 打印1~100
*/
public synchronized void task3() {
for (int i = 0; i < 100; i++) {
System.out.print(i);
}
System.out.println();
}
}
package demo1;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Test {
/**
* 需求1:
* 线程同步执行三个任务
*/
public static void main(String[] args) {
//线程池a
ExecutorService pool = Executors.newFixedThreadPool(3);
//任务类
final Function function = new Function();
//线程1
pool.execute(new Runnable() {
@Override
public void run() {
function.task1();
}
});
//线程2
pool.execute(new Runnable() {
@Override
public void run() {
function.task2();
}
});
//线程3
pool.execute(new Runnable() {
@Override
public void run() {
function.task3();
}
});
//关闭线程
pool.shutdown();
}
}
需求2:
package demo2;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Test {
/**
* 需求2: 多线程执行任务: 任务:产生随机数,并睡眠,显示打印,最后退出
*/
public static void main(String[] args) {
// 创建动态线程池
ExecutorService pool = Executors.newCachedThreadPool();
final Lock lock = new ReentrantLock();
// 产生随机数(1-10),并循环创建线程
for (int i = 0; i < new Random().nextInt(10) + 1; i++) {
pool.execute(new Runnable() {
@Override
public void run() {
// 加入锁
lock.lock();
try {
// 随机数
int sleepTime = new Random().nextInt(20) + 1;
Thread.sleep(sleepTime * 1000);
System.out.println(Thread.currentThread().getName() + ":睡眠" + sleepTime + "秒");
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
});
}
// 关闭
pool.shutdown();
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询