/**
* 继承 thread 的内部类,以买票例子
*/
public class FirstThread extends Thread{
private int i;
private int ticket = 10;
@Override
public void run() {
for (;i<20;i++) {
//当继承thread 时,直接使用this 可以获取当前的线程,getName() 获取当前线程的名字
// Log.d(TAG,getName()+" "+i);
if(this.ticket>0){
Log.e(TAG, getName() + ", 卖票:ticket=" + ticket--);
}
}
}
}
private void starTicketThread(){
Log.d(TAG,"starTicketThread, "+Thread.currentThread().getName());
FirstThread thread1 = new FirstThread();
FirstThread thread2 = new FirstThread();
FirstThread thread3 = new FirstThread();
thread1.start();
thread2.start();
thread3.start();
//开启3个线程进行买票,每个线程都卖了10张,总共就30张票
}
/**
* 实现 runnable 接口,创建线程类
*/
public class SecondThread implements Runnable{
private int i;
private int ticket = 100;
@Override
public void run() {
for (;i<20;i++) {
//如果线程类实现 runnable 接口
//获取当前的线程,只能用 Thread.currentThread() 获取当前的线程名
Log.d(TAG,Thread.currentThread().getName()+" "+i);
if(this.ticket>0){
Log.e(TAG, Thread.currentThread().getName() + ", 卖票:ticket=" + ticket--);
}
}
}
}
private void starTicketThread2(){
Log.d(TAG,"starTicketThread2, "+Thread.currentThread().getName());
SecondThread secondThread = new SecondThread();
//通过new Thread(target,name)创建新的线程
new Thread(secondThread,"买票人1").start();
new Thread(secondThread,"买票人2").start();
new Thread(secondThread,"买票人3").start();
//虽然是开启了3个线程,但是一共只买了100张票
}
/**
* 使用callable 来实现线程类
*/
public class ThirdThread implements Callable<Integer>{
private int ticket = 20;
@Override
public Integer call(){
for ( int i = 0;i<10;i++) {
//获取当前的线程,只能用 Thread.currentThread() 获取当前的线程名
// Log.d(TAG,Thread.currentThread().getName()+" "+i);
if(this.ticket>0){
Log.e(TAG, Thread.currentThread().getName() + ", 卖票:ticket=" + ticket--);
}
}
return ticket;
}
}
private void starCallableThread(){
ThirdThread thirdThread = new ThirdThread();
FutureTask<Integer> task = new FutureTask<Integer>(thirdThread);
new Thread(task,"有返回值的线程").start();
try {
Integer integer = task.get();
Log.d(TAG,"starCallableThread, 子线程的返回值="+integer);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有