赞
踩
- package com.it;
-
- /**
- * 通过Runnable接口创建线程
- */
- public class TestThread01 implements Runnable {
- @Override
- public void run() {
- for (int i = 0; i < 10; i++) {
- System.out.println(Thread.currentThread().getName()+":"+i);
- }
- }
-
- public static void main(String[] args) {
- TestThread01 t = new TestThread01();
- // 把实现了Runnable接口的对象作为参数传入
- Thread t1 = new Thread(t);
- t1.start();
-
- Thread t2 = new Thread(t);
- t1.start();
- }
-
- }

- package com.it;
-
- /**
- * 使用lambda表达式创建线程
- */
- public class TestThread02 {
- public static void main(String[] args) {
- // 通过匿名内部类的方式创建线程
- new Thread(new Runnable() {
- @Override
- public void run() {
- for (int i = 0; i < 10; i++) {
- System.out.println(Thread.currentThread().getName()+":"+i);
- }
- }
- }).start();
-
- new Thread(()->{
- for (int i = 0; i < 10; i++) {
- System.out.println(Thread.currentThread().getName()+":"+i);
- }
- }).start();
- }
- }

- package com.it;
-
- /**
- * 测试终止线程的典型方法
- */
- public class TestThreadCycle_Terminated implements Runnable{
- boolean live = true;//标记线程是否可以结束
-
- @Override
- public void run() {
- int i =0;
- while(live){
- System.out.println(Thread.currentThread().getName()+":"+i++);
- }
- }
-
- public void terminate(){
- live = false;
- }
-
- public static void main(String[] args) {
- TestThreadCycle_Terminated tt = new TestThreadCycle_Terminated();
- Thread t = new Thread(tt);//新生状态
- t.start();//就绪状态
-
- for (int i = 0; i < 10; i++) {
- System.out.println("主线程"+i);
- }
-
- tt.terminate();//结束线程
- System.out.println("tt线程结束");
- }
-
-
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。