之前一直看了不少的java线程的例子,很多老师都说得没错,要学好程序是不能只单纯看的,很多东西能够看得懂,但这不意味着能够写的出来。
     我今晚没有看书凭自己的感觉写了个很简单的线程例子,说实话,虽然真的很简单,但是却没什么头绪。一边做一边看了API文档。自己动手了,确实也有点收获。
程序代码是: 
 

 Code
Code
 1 public class MyThread extends Thread{
 2     public MyThread() throws InterruptedException{
 3         String th2 = "producer";
 4     
 5         for (int j = 0; j <= 2; j++) {
 6             System.out.println(th2);
 7             if(j==1) {            
 8             System.out.println("Hello");
 9             }
10         }
11     }
12     
13     
14     public void run(){
15         // TODO 自动生成方法存根        
16     
17         try {
18             String th1 = "consumer";
19             for (int i = 0; i <= 2; i++) {
20                 System.out.println(th1);            
21             Thread.sleep(1000);
22             }
23         }
24         catch(InterruptedException e) {
25             System.out.println("有停顿了吗?");
26         }
27 }
28 
29     
30     
31     public static void main(String[] arg) throws InterruptedException {
32         MyThread youthread=new MyThread();
33         //Thread th=new Thread(youthread);
34         youthread.start();
35         //th.start();
36     }
37     
38 }
39      1、对于这道程序,如果实现Runable接口的话,只需实run()方法,启动线程为:MyThread youthread=new MyThread();Thread th=new Thread(youthread);    th.start();
     2、如果不是实现Runnable接口,而是继承Thread类;则我们可以这样写:MyThread youthread=new MyThread();
youthread.start(); 
    这是我今晚我写这道简单线程的体会。