多线程 编写多线程的两种方式

1、通过继承Thread编写多线程类

 1 package org.zln.thread;
 2 
 3 import java.util.Date;
 4 
 5 /**
 6  * Created by coolkid on 2015/6/21 0021.
 7  */
 8 public class TestThread extends Thread{
 9     private int time;//休眠时间
10     private String user;//调用用户
11 
12     public TestThread(int time, String user) {
13         this.time = time;
14         this.user = user;
15     }
16 
17     @Override
18     public void run() {
19         while (true){
20             try {
21                 System.out.println(Thread.currentThread().getName()+"\t"+user+" 休息 "+time+"ms-"+new Date());
22                 Thread.sleep(time);
23             } catch (InterruptedException e) {
24                 e.printStackTrace();
25             }
26         }
27     }
28 
29     public static void main(String[] args) {
30         Thread thread1 = new TestThread(1000,"Jack");
31         Thread thread2 = new TestThread(3000,"Mike");
32         thread1.start();
33         thread2.start();
34     }
35 }
E:\GitHub\tools\JavaEEDevelop\Lesson1_JavaSe_Demo1\src\org\zln\thread\TestThread.java

设置线程优先级:thread2.setPriority(Thread.MAX_PRIORITY);

这样就能够保证每次都是thread2先于thread1执行

2、通过实现Runnable接口编写多线程类

 1 package org.zln.thread;
 2 
 3 import java.util.Date;
 4 
 5 /**
 6  * Created by coolkid on 2015/6/21 0021.
 7  */
 8 public class TestRunnable implements Runnable {
 9     private int time;//休眠时间
10     private String user;//调用用户
11 
12     public TestRunnable(int time, String user) {
13         this.time = time;
14         this.user = user;
15     }
16 
17     @Override
18     public void run() {
19         while (true){
20             try {
21                 System.out.println(Thread.currentThread().getName()+"\t"+user+" 休息 "+time+"ms-"+new Date());
22                 Thread.sleep(time);
23             } catch (InterruptedException e) {
24                 e.printStackTrace();
25             }
26         }
27     }
28 
29     public static void main(String[] args) {
30         Thread t1 = new Thread(new TestRunnable(1000,"Jack"));
31         Thread t2 = new Thread(new TestRunnable(3000,"Mike"));
32         t2.setPriority(Thread.MAX_PRIORITY);
33         t1.start();
34         t2.start();
35     }
36 }
E:\GitHub\tools\JavaEEDevelop\Lesson1_JavaSe_Demo1\src\org\zln\thread\TestThread.java

 

转载于:https://www.cnblogs.com/sherrykid/p/4592347.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值