Thread与Runnable实现线程利用线程插队实现求和操作

--------------------实现线程的两种方式-----------------

package com.tangkuo.thread.cn;
/**
*
* @author tangkuo
*
*/
public class ThreadDemo extends Thread{

/**
* 线程 每次输出一个数字,休眠5秒钟
* 打印当前线程的名字与输出的数字值
*
*/
@Override
public void run(){
for(int i = 0; i < 10; i++){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("新线程"+ Thread.currentThread().getName()+"输出"+i);
}
}
public static void main(String[] args) {
ThreadDemo thread1 = new ThreadDemo();
ThreadDemo thread2 = new ThreadDemo();
thread1.start();
thread2.start();
for(int i = 0; i < 10; i++){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("主线程"+ Thread.currentThread().getName()+"输出"+i);
}
}


}


package com.tangkuo.thread.cn;

public class RunnableDemo implements Runnable {

@Override
public void run() {
for(int i = 0; i < 10; i++){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("新线程"+ Thread.currentThread().getName()+"输出"+i);
}

}

public static void main(String[] args) {
RunnableDemo runnableDemo = new RunnableDemo();
//Runnable runnableDemo = new RunnableDemo();

Thread thread1 = new Thread(runnableDemo);
Thread thread2 = new Thread(runnableDemo);
thread1.start();
thread2.start();
for(int i = 0; i < 10; i++){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("主线程的名字"+ Thread.currentThread().getName()+"输出值"+i);
}
}

}


package com.tangkuo.thread.cn;
/**
* 利用线程插队求和
* @author Administrator
*
*/
public class SumRunnableDemo implements Runnable {
private int x;
private int y;
private long sum;

@Override
public void run() {
for(int i = x; i < y; i++){
sum +=i;
}
}

public SumRunnableDemo(int x, int y) {
super();
this.x = x;
this.y = y;
System.out.println(x+"到"+y+"之间的和等于");
}

public long getSum() {
return sum;
}



public static void main(String[] args) {
SumRunnableDemo srd = new SumRunnableDemo(1,100);
Thread thread = new Thread(srd);
thread.start();
//线程插队求和
try {
thread.join();//主线程必须等子线程执行完毕才能运行关闭。保证子线程所有业务逻辑处理完成
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("sum="+srd.getSum());
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值