线程的两种创建方式
来源:互联网 发布:淘宝小李子 编辑:程序博客网 时间:2024/04/29 22:12
继承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); } } }
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(); } }
0 0
- 创建线程两种方式的比较
- java 创建线程 的两种方式
- 创建线程两种方式的比较
- 创建线程的两种方式
- 创建线程的两种方式
- 多线程 创建线程的两种方式
- 创建线程的两种方式
- Java线程创建的两种方式
- 创建线程的两种方式
- 创建线程的两种方式
- 创建线程的两种方式。
- java创建线程的两种方式
- 线程的两种创建方式
- java创建线程的两种方式
- java线程的两种创建方式
- Java创建线程的两种方式
- 线程创建的两种方式
- 创建线程的两种方式
- Java Url请求方式中文乱码问题解决办法
- sicily 2501. 算算式
- Oracle 类型转换参考
- 使用python编译Cocos2d-x3.9的cpp-tests文件夹下的所有项目
- Linux使用SSH安全登录
- 线程的两种创建方式
- 使用GoAccess分析Nginx日志
- PHP程序员的成长之路
- UITableView系列——基本介绍
- 设计模式
- 公有IP地址与私有IP地址
- 工具软件APP tune-up Kit分析
- Android App 线上热修复方案
- android 5.0 新特性