Java学习笔记-Thread-线程
//2015年5月5日16:55:00
//Main
package com.alfredsun.thread; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub MyThread t1=new MyThread("A"); MyThread t2=new MyThread("B"); // t1.run(); // t2.run(); //线程的启动由start() t1.start(); t2.start(); } }
//MyThread
package com.alfredsun.thread; public class MyThread extends Thread { private String name; public MyThread(String name) { this.name =name; } public void run() { for(int i=0;i<10;i++) { System.out.println(name+":"+i); } super.run(); } }
//并发结果
A:0 B:0 A:1 B:1 A:2 B:2 A:3 B:3 A:4 B:4 A:5 B:5 B:6 A:6 B:7 A:7 B:8 B:9 A:8 A:9
//Runnable接口
//2015年5月5日17:04:03
//main package com.alfredsun.thread; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub MyRunable r1= new MyRunable("A"); MyRunable r2=new MyRunable("B"); Thread t1=new Thread(r1); Thread t2=new Thread(r2); t1.start(); t2.start(); } }
//Myrunnable package com.alfredsun.thread; public class MyRunable implements Runnable { private String name; public MyRunable(String name) { this.name=name; } public void run() { for(int i=0;i<1000;i++) { System.out.println(name+":"+i); } } }
//线程的操作
//2015年5月5日17:31:47
1 package com.alfredsun.thread; 2 class RunnableDemo implements Runnable 3 { 4 private String name; 5 public RunnableDemo(String name) { 6 this.name =name; 7 } 8 public void run() 9 { 10 for(int i=0;i<50;i++) 11 { 12 System.out.println(Thread.currentThread().getName()); 13 } 14 } 15 } 16 public class test { 17 public static void main(String[] args) 18 { 19 RunnableDemo r1= new RunnableDemo("A"); 20 RunnableDemo r2= new RunnableDemo("B"); 21 Thread t1 =new Thread(r1); 22 Thread t2 =new Thread(r2); 23 24 t1.start(); 25 t2.start(); 26 } 27 }