文档详情

Java线程详解教学提纲.ppt

发布:2020-06-02约3.42千字共45页下载文档
文本预览下载声明
多线程;进程和线程;进程;进程;线程(threads);线程;多线程;Thread;线程状态;Thread;Thread;public class TestThread { public static void main(String[] args) { MyThread myThread = new MyThread(); myThread.setName(myThread);//设置线程的名称 myThread.start();//启动线程 for(int i=0;i100;i++){ //主线程 System.out.println(Thread.currentThread().getName() + “*** + i); } } } class MyThread extends Thread { //需要在线程中运行的代码写在run方法中 public void run() { for (int i = 0; i 100; i++) { //获得当前执行的线程的名称 System.out.println(Thread.currentThread().getName() + --- + i); } } };Runnable;实现Runnable接口;线程的生命周期;分析两种实现多线程的方式:;继承Thread,每个线程卖了100张票 [没有共享数据] public class TicketThread { public static void main(String[] args){ // 执行继承Thread的线程 new MyThread().start(); new MyThread().start(); new MyThread().start(); new MyThread().start(); } } class MyThread extends Thread { // 车票数量 private int tickets = 100; public void run() { while (tickets 0) { System.out.println(this.getName()+卖出第[+(tickets--)+]张火车票); } } };实现Ruaable,线程总共卖100张票[有共享数据] public class TicketRunnable { public static void main(String[] args) { //实现Runnable接口实现类 myRunnable myR = new myRunnable(); new Thread(myR).start(); new Thread(myR).start(); new Thread(myR).start(); new Thread(myR).start(); } } class myRunnable implements Runnable { //火车票数量 private int tickets = 100; public void run() { while (tickets 0) { System.out.println(Thread.currentThread().getName()+卖出第[+(tickets--) +]张火车票.); } } };两种线程创建方式的比较;阻塞和解除阻塞;线程状态;与线程控制有关的方法;线程状态; class MyThread extends Thread{ public void run(){ long start = new Date().getTime(); for(int i=0;i100;i++){ if(this.getName().equals(t2)){ Thread.yield(); } System.out.print(this.getName() + : + i + \t); } long end = new Date().getTime(); Syst
显示全部
相似文档