黑马程序员-java的多线程的练习

时间:2021-11-16 00:27:28
package com.itheima;

public class Tetsover {
public static void main(String []args){
for (int i = 0; i < 10; i++) {
Thread thread=new Threader();
thread.start();
}
try {
Thread.sleep(3000);//过3秒使用runnable
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Runer rr=new Runer();
for (int i = 0; i < 10; i++) {
Thread yThread=new Thread(rr);
yThread.start();
}
}
}
class Threader extends Thread{
public int x=0;
@Override
public void run() {
System.out.println(++x+"thread");
}
}
class Runer implements Runnable{

private int x=0;

@Override
public void run() {
System.out.print(x+"runable");
}
}


这个是我自己根据网上做的java的小练习,然后根据毕向东老师讲解的线程的知识章节,想起了 android的 线程机制和消息机制问题,

做了如下的小练习。

片段1:

private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {// 事件处理机制
switch (msg.arg1) {
case 0:
newsDetails.setText(Html.fromHtml(msg.obj.toString()));
break;
}
}
};


片段2:

 

// 启动一个线程去执行。
private class UpdateNewsThread extends Thread {

@Override
public void run() {
String newsBody = getNewsBody();
Message msg = mHandler.obtainMessage();
msg.arg1 = FINISHED;
msg.obj = newsBody;
mHandler.sendMessage(msg);
}

}


然后又把自己曾看过 老罗的一拍照上传的一代代码写了一下

片段:

new Thread(new Runnable() {

@Override
public void run() {
try {
HttpClient httpClient=new DefaultHttpClient();
HttpPost post=new HttpPost(path);
MultipartEntity entit=new MultipartEntity();
entit.addPart("myfile",new ByteArrayBody(filebody, filename));
post.setEntity(entit);

httpClient.execute(post);
} catch (Exception e) {
// TODO: handle exception
}

}
}).start();


一直感觉线程机制也好,Android的异步也好,都是很棒的,异步更是在对多线程的封装,通过对java的基础的学习,和以前自学的Android的一些基础知识

现在对线程有了新的认识,比如线程之间的安全问题,线程之间的通信,线程和消息机智的结合等等。

                                                                         ------- android培训java培训IOS培训.Net培训期待与您交流! ----------