创建两个线程,实现两个相同的耗时任务
实现2个窗口同时卖火车票;每个窗口卖100张,卖票速度都是1s/张,最后弹出通知票已卖完。
public class MainActivity extends AppCompatActivity {
private Button button2;
private Handler handler=new Handler(){
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
String s= (String) msg.obj;
switch (msg.what){
case 1:
Toast.makeText(MainActivity.this,s,Toast.LENGTH_SHORT).show();
break;
case 2:
Toast.makeText(MainActivity.this,s,Toast.LENGTH_SHORT).show();
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button2=findViewById(R.id.bt2);
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int ticket=100;
new Thread(new Runnable() {
@Override
public void run() {
for (int i=0;i<=ticket;i++){
int n=ticket-i-1;
Log.i("窗口1","卖掉了1张票,剩余票数:"+n);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Message msg=Message.obtain();
msg.what=1;
msg.obj="窗口一电影票已卖完";
handler.sendMessage(msg);
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
for (int i=0;i<=ticket;i++){
int n=ticket-i-1;
Log.i("窗口2","卖掉了1张票,剩余票数:"+n);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Message msg=Message.obtain();
msg.what=1;
msg.obj="窗口二电影票已卖完";
handler.sendMessage(msg);
}
}).start();
}
});
}
}
|