java多线程编程

半陌 2017-10-13 01:00:03
编写一个线程,有一个成员变量(类型自己定义),2个构造函数,一个无参,一个有一个参数,该线程能够生成随机的int值给成员变量使用,并且在控制台打印出来,要求:写一个main函数,函数里面3次调用定义好的线程,并且在3个线程都执行完成后,控制台打印出3个线程生成的int型随机数加起来的和。(期望带有源码)
考核点:多线程,同步辅助类;
...全文
245 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
xiaouer2529586 2017-10-13
  • 打赏
  • 举报
回复
public class test2 implements Callable<Integer>{ private int value; public test2(){ } public test2(int value){ this.value = value; } @Override public Integer call() { value = new Random().nextInt(100); System.out.printf("当前线程为:%s,输出value值:%d",Thread.currentThread().getName(),value); System.out.println(); return value; } public static void main(String[] args) { ExecutorService executors = Executors.newCachedThreadPool(); int sum = 0; List<Future<Integer>> results = new ArrayList<Future<Integer>>(); for (int i=0;i<3;i++){ results.add(executors.submit(new test2())); } for (Future<Integer> result : results) { try { sum += result.get(1000, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } catch (TimeoutException e) { e.printStackTrace(); } finally { executors.shutdown(); } } System.out.println(sum); } }
自由自在_Yu 2017-10-13
  • 打赏
  • 举报
回复
public class Test extends Thread {
	private int a;
	public Test() {}

	public Test(int a) {
		this.a = a;
	}
	
	public static void main(String[] args) throws InterruptedException {
		int sum = 0;
		for (int i = 0; i < 3; i++) {
			Test test = new Test();
			test.start();
			sleep(100);
			System.out.print(test.a+"  ");
			sum += test.a;
		}
		System.out.println();
		System.out.println(sum);
	}

	public void run() {
		a = (int) (Math.random()*10);
	}
}

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧