线程的两种创建方式
2015-11-19 14:38
471 查看
继承Thread类:
/** * 方法一: * 继承Thread类创建线程 * @author LiMin * */ public class CreateThread extends Thread { private String name; public CreateThread(){ } public CreateThread(String name){ /*this.name=name;*/ //调用父类的给线程命名的方法 super(name); } public void run(){ for(int x =0;x<60;x++){ /*System.out.println(this.name+ " run -----"+ x);*/ /*System.out.println(this.getName()+ " run -----"+ x);*/ //使用Thread的静态方法获取线程名称Thread.currentThread().getName()是标准通用方式 /*System.out.println(Thread.currentThread().getName()+ " run -----"+ x);*/ System.out.println((Thread.currentThread()==this)+"....."+this.getName()+ " run -----"+ x); } } }调用:
public class ThreadTest { /** * @param args */ public static void main(String[] args) { CreateThread t1 = new CreateThread("one----"); CreateThread t2= new CreateThread("two+++++"); t1.start(); t2.start(); for(int x =0;x<60;x++){ System.out.println("main-----"+ x); } } }实现Runnable接口:
public class Ticket2 implements Runnable{ //extends Thread{//如果是静态的话,所有的线程会共享这100张票/*private static int ticket =100;*///如果不是静态的话,每一个线程对象都会创建这个ticket对象,也即每个线程拥有100张票卖。//这时候,如果还是采用继承Thread类的方法就不行了,需要使用实现Runnable接口创建线程private int ticket =1000;Object obj= new Object();public void run() {//在这里声明的对象是无效的/*Object obj= new Object(); */while(true){synchronized (obj) {if(ticket>0){try {Thread.sleep(10);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(Thread.currentThread().getName()+".....sale : "+ ticket--);}}}}}调用:
public class TicketDemo2 {/*** @param args*/public static void main(String[] args) {Ticket2 t = new Ticket2();Thread t1 = new Thread(t);Thread t2 = new Thread(t);Thread t3 = new Thread(t);Thread t4 = new Thread(t);t1.start();t2.start();t3.start();t4.start();}}
相关文章推荐
- hibernate入门(一)
- 为什么Excel创建一个新的工作簿就会初始化三个worksheet
- Linux设备驱动之mmap设备操作
- 参数 of jQuery.ajax()
- linux非专业常用命令
- org.hibernate.QueryException: could not resolve property
- MyEclipse8.5 + jdk 1.6.0_43 + tomcat6 + maven 3.0.4 + win7 32位 ,环境搭建并看到“hello world”
- OS X 10.11 安装Cocoapods
- Android音频系统之音频框架
- JBPM4 常用表结构详解,转自:http://blog.csdn.net/liulgcq/article/details/7205950
- Flume + HDFS Sink采集数据及如何添加第三方JAR
- retrofit2.0转换String 报错修复
- 看到C上这么多努力的大神有感
- swif自学笔记(二)
- [Leetcode]Search a 2D Matrix II
- block的简单回调传值
- Servlet:JSP理解
- linker command failed with exit code 1
- About ANR and OOM
- Asp.Net HttpApplication请求管道与Session(二)