我在onCreate方法中使用以下代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
ServerSocket serverSocket = new ServerSocket(9002);
Socket s = serverSocket.accept();
DataOutputStream outputStream = new DataOutputStream(
s.getOutputStream());
BufferedReader inputStream = new BufferedReader(
new InputStreamReader(s.getInputStream()));
outputStream.write("Howdy! newbie".getBytes());
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
thread.run();
}
});
}
它给了我一个NetworkOnMainThreadException!
当我使用以下行删除限制时,它确实有效:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
但我为什么要用呢?
我使用了线程,为什么它不在分离的线程上运行并在UI线程上运行?!
答案 0 :(得分:8)
更改
thread.run();
到
thread.start();
<强>差:强>
Thread.run()不会产生新线程,而 Thread.start() 是的,即
Thread.run
实际上运行在与...相同的线程上 调用者而Thread.start()
创建一个新任务的线程 跑了。
答案 1 :(得分:2)
因为你没有要求线程启动。
替换:
thread.run();
用
thread.start();
调用run()
只会在当前线程上执行提供的Runnable
。但是,start()
会将执行产生到新线程上。
答案 2 :(得分:2)
thread.run()
更改为thread.start()
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
ServerSocket serverSocket = new ServerSocket(9002);
Socket s = serverSocket.accept();
DataOutputStream outputStream = new DataOutputStream(
s.getOutputStream());
BufferedReader inputStream = new BufferedReader(
new InputStreamReader(s.getInputStream()));
outputStream.write("Howdy! newbie".getBytes());
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
thread.start();
}
});
}