首页 > 学院 > 开发设计 > 正文

创建线程的两个方式

2019-11-14 21:45:07
字体:
来源:转载
供稿:网友
创建线程的两个方式

方式一:

package com.Thread1;public class myRunable implements Runnable {public int count;@Overridepublic void run() {while (count < 100) {count++;System.out.PRintln("count:" + count + "由"+ Thread.currentThread().getName() + "创建");}}}

package com.Thread1;public class myRunableTest {public static void main(String[] args) {Thread t1 = new Thread(new myRunable(), "线程1");t1.start();Thread t2 = new Thread(new myRunable(), "线程2");t2.start();}}

方式二:

package com.Thread1;public class MyThread1 extends Thread {public int count;@Overridepublic void run() {while (count <100) {count++;System.out.println("count:"+count+"由"+Thread.currentThread().getName()+"创建");}}}

package com.Thread1;public class MyThread1Test {public static void main(String[] args) {// MyThread1 mt1 = new MyThread1();// Thread t = new Thread(mt1);// t.start();Thread t1 = new MyThread1();t1.setName("线程1");t1.start();Thread t2 = new MyThread1();t2.setName("线程2");t2.start();}}

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表