多线程的创建
来源:互联网 发布:c语言经典编程题pdf 编辑:程序博客网 时间:2024/04/28 13:49
用Runnable 接口创建多线程程序,先对其以方法来实现,后用Thread来创建线程,用go类来调用并执行线程,然后在主类中实例化,并调用其中的gogo方法()来执行(go方法我只是对线程可否在子类中被Mian类调用有些疑问,证明是可以的)。
public class CreatThread { public static void main(String args[]) { //主线程 go goo =new go(); goo.gogo(); for(int i=1;i<=15;i++) { System.out.print("主人"+i+" "); } }}public class SpeakCar implements Runnable { public void run() { for(int i=1;i<=20;i++) { System.out.print("轿车"+i+" "); } } }public class SpeakElephant implements Runnable { public void run() { for(int i=1;i<=20;i++) { System.out.print("大象"+i+" "); } } }public class go { void gogo(){ SpeakElephant speakElephant = new SpeakElephant() ; //创建线程 SpeakCar speakCar = new SpeakCar(); //创建线程 Thread Selepant = new Thread(speakElephant); Thread Scar = new Thread(speakCar); Selepant.start(); //启动线程 Scar.start(); //启动线程 }}
还有另一类创建方法:将线程定义在Runnable的实现类中
currentThread()作用是返回当前占用cpu使用权的线程名
sleep(int time)的作用是使线程休眠,单位是毫秒
interrupt()作用是吵醒休眠的线程
public class Example12_6 { public static void main(String args[]) { ClassRoom room6501=new ClassRoom(); room6501.student.start(); room6501.teacher.start(); }}public class ClassRoom implements Runnable { Thread student,teacher; ClassRoom() { teacher=new Thread(this); student=new Thread(this); teacher.setName("王教授"); student.setName("张三"); } public void run(){ if(Thread.currentThread()==student) { try{ System.out.println(student.getName()+"正在睡觉,不听课"); Thread.sleep(1000*60*60); } catch(InterruptedException e) { System.out.println(student.getName()+"被老师叫醒了"); } System.out.println(student.getName()+"开始听课"); } else if(Thread.currentThread()==teacher) { for(int i=1;i<=3;i++) { System.out.println("上课!"); try{ Thread.sleep(500); } catch(InterruptedException e){} } student.interrupt(); //吵醒student } }}
0 0
- 闲话多线程的创建
- 创建多线程的HttpClient
- pthread多线程的创建
- 多线程的创建方式
- 多线程的创建例子
- C#多线程的创建
- C# 多线程的创建
- 闲话多线程的创建
- 多线程的创建
- IOS-多线程的创建
- 多线程的创建
- 多线程的创建方式
- C# 多线程的创建
- 多线程的创建问题
- 多线程的创建
- 多线程的创建
- MFC多线程的创建
- java多线程的创建
- 内部排序-堆排序
- LeetCode 213:House Robber II
- 提问的智慧
- Java NIO使用及原理分析 (一)
- Linux 递归经典:fork 炸弹
- 多线程的创建
- 黑马程序员--C语言自学笔记---04分支结构
- 数组和指针
- 进击的KFC:UI(14)集合视图UICollectionView
- 递归读取heritrix 爬下来的目录文件
- StringBuffer类常用方法(Java)
- 前端小工具集合
- [Coursera]算法基础_Week9_考试_Q2
- 第4天