gpt4 book ai didi

java - 为什么我的代码运行在主线程上?

转载 作者:太空狗 更新时间:2023-10-29 15:36:09 26 4
gpt4 key购买 nike

我在 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线程上?!

最佳答案

改变

thread.run();

thread.start();

区别:

Thread.run() does not spawn a new thread whereas Thread.start() does, i.e Thread.run actually runs on the same thread as that of the caller whereas Thread.start() creates a new thread on which the task is run.

有关详细信息,请参阅 Difference between running and starting a thread

关于java - 为什么我的代码运行在主线程上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25324248/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com