Java多线程

ctmuziniao 2019-04-17 11:38:23
a)使用Runnable接口创建多线程程序,其中一个线程输出数字0-100,另一个线程计算100-1000的和,并打印结果.



b)创建一个多线程程序,程序中一个线程循环输出0-100;另一个线程循环输出1000-1100;输出格式为: 线程名+数字。
...全文
115 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
第一名zz 2019-04-18
  • 打赏
  • 举报
回复
我来写一下第二题

public class ThreadTest3 {

	public static void main(String[] args) {
		
		Count count1 = new Count(0, 100);
		Count count2 = new Count(1000, 1100);
		Thread thread1 = new Thread(count1);
		Thread thread2 = new Thread(count2);
		thread1.start();
		thread2.start();

	}
}

// 输出数字
class Count implements Runnable {

	int start;
	int end;

	public Count(int start, int end) {
		super();
		this.start = start;
		this.end = end;
	}

	@Override
	public void run() {
		for (int i = start; i <= end; i++) {
			//Thread.currentThread().getName()打印线程名字
			System.out.println(Thread.currentThread().getName() + "--" + i);
		}
	}

}

hei__ke 2019-04-17
  • 打赏
  • 举报
回复
final int time = 3000;
Runnable runnable = new Runnable(){
public void run(){
while (true){
System.out.println("自动任务");

try {
Thread.sleep(time);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
Thread thread = new Thread(runnable);
thread.start();
这样感觉更明了一些吧
十八道胡同 2019-04-17
  • 打赏
  • 举报
回复
package com.demo;
public class Test06 {
    public static void main(String[] args) {
        new Thread(new SubThread2(0, 100)).start();
        new Thread(new SubThread(1000, 1100)).start();
    }

    public static class SubThread implements Runnable {
        private Integer startIndex;
        private Integer endIndex;
        public ThreadLocal<Integer> Count = new ThreadLocal<Integer>();

        SubThread(Integer start, Integer end) {
            startIndex = start;
            endIndex = end;
        }

        @Override
        public void run() {
            Count.set(0);
            for (int i = startIndex; i <= endIndex; i++) {
                    Count.set(Count.get() + i);
            }
            System.out.println(startIndex + "到" + endIndex + "共有" + Count.get());
        }
    }
    public static class SubThread2 implements Runnable {
        private Integer startIndex;
        private Integer endIndex;

        SubThread2(Integer start, Integer end) {
            startIndex = start;
            endIndex = end;
        }

        @Override
        public void run() {
            for (int i = startIndex; i <= endIndex; i++) {
                System.out.println(i);
            }
        }
    }



}

62,628

社区成员

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

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