1.java中有Thread 和 Runnable两种实现线程的方式。
package thread;
public class MyThread extends Thread{
private String name;
private int tick = 10;
public MyThread(String name){
this.name = name;
}
public void run (){
for(int i = 1;i <= tick;i ++){
System.out.println("线程开始:"+this.name+" " +i);
}
}
public static void main(String[] args) {
MyThread t1 = new MyThread("线程A");
MyThread t2 = new MyThread("线程B");
MyThread t3 = new MyThread("线程C");
// t1.run();
// t2.run();
t1.start();
t2.start();
t3.start();
}
}
package thread;
public class MyRunnable implements Runnable{
private String name;
private int tick = 10;
public MyRunnable(String name){
this.name = name;
}
public void run() {
for(int i = 0;i < 20 ;i ++){
if(tick>0)
System.out.println(this.name + tick--);
}
}
public static void main(String[] args) {
MyRunnable mr1 = new MyRunnable("A");
// MyRunnable mr2 = new MyRunnable("B");
mr1.run();
// mr2.run();
new Thread(mr1).start();
new Thread(mr1).start();
new Thread(mr1).start();
}
}
线程池:
package thread;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ExecuteServiceTest {
public static void main(String[] args) {
ExecutorService threadPool = Executors.newCachedThreadPool();
/**
* 缓存线程池
*/
for(int i = 0;i < 10;i ++){
threadPool.execute(new Runnable(){
public void run(){
for(int i = 0;i < 10;i ++){
System.out.println(Thread.currentThread().getName());
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
}
}
}