java的线程
2016-05-05 21:13
387 查看
多任务与多线程:多任务属于系统级的各个应用之间的关系,而多线程属于应用级的一个应用的多个功能之间的关系
创建线程的两种方式:
实现Runnable接口
class sunclass {}
class SumThread extends sumclass imlements Runnable{}
public class **{public void main(){SumThread st=new SumThread();Thread t=new Thread(st,"threadname");t.start();}}
继承Thread类(直接继承thread类,或者使用匿名嵌套类)
创建线程的两种方式:
实现Runnable接口
class sunclass {}
class SumThread extends sumclass imlements Runnable{}
public class **{public void main(){SumThread st=new SumThread();Thread t=new Thread(st,"threadname");t.start();}}
继承Thread类(直接继承thread类,或者使用匿名嵌套类)
class SumThread extends Thread{ private long length; public SumThread(long length,String name){ super(name); this.length=length; } public void run(){ long temp=0; for(int i=1;i<=length;i++){ try { Thread.sleep((int)(Math.random()*10)); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } temp+=i; } System.out.println(Thread.currentThread()+"zonghe:"+temp); } } public class Thread1 { public static void main(String[] args) { System.out.println("线程"); System.out.println(Thread.currentThread()); SumThread st1=new SumThread(150,"线程1"); st1.start(); new Thread("线程2"){ int length=150; public void run(){ long temp=0; for(int i=1;i<=length;i++){ try { Thread.sleep((int)(Math.random()*10)); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } temp+=i; } System.out.println(Thread.currentThread()+"zonghe:"+temp); } }.start(); }}
相关文章推荐
- Spring的反射工具类 ReflectionUtils
- JAVA——集合类
- Getting Spring Error “Bean named 'x' must be of type [y], but was actually of type [$Proxy]” in Jenk
- Spring AOP 之 实现切点、切面
- java classloader机制
- java junit测试
- Spring AOP 深入分析
- IDEA+Maven+Spring+SpringMVC+SpringJDBC整合Demo
- 八大排序算法 之 基数排序(桶排序)
- java的异常处理
- Quartz使用-入门使用(java定时任务实现)
- Java删除文件夹和文件
- Spring 中 MultipartResolver
- spring从头开始(一)
- 排序算法java 二 --基数排序、归并排序
- Java集合框架
- druid在spring中的配置已经maven中的配置
- Java中数字字符串与对应数字的转换
- 官网下载java相关资源
- java常用类