线程是进程中可独立执行的最小单位,也是 CPU 资源分配的基本单位。
2. 线程的四个属性(1)编号Idpublic class MyTask implements Callable<Object>{
private String args1;
private String args2;
//构造函数,用来向task中传递任务的参数
public MyTask(String args1,String args2) {
this.args1=args1;
this.args2=args2;
}
//任务执行的动作
@Override
public Object call() throws Exception {
for(int i=0;i<100;i++){
System.out.println(args1+args2+i);
}
return true;
}MyTask myTask = new MyTask("www", "www");
FutureTask<Object> futureTask = new FutureTask<>(myTask);
Thread thread = new Thread(futureTask);
thread.start();
//get()阻塞等待直到任务执行完成。
boolean result = (boolean) futureTask.get();
public class LockSupportTest {
public static void main(String[] args) {
Thread parkThread = new Thread(new ParkThread());
parkThread.start();
System.out.println("开始线程唤醒");
LockSupport.unpark(parkThread);
System.out.println("结束线程唤醒");
}
static class ParkThread implements Runnable{
@Override
public void run() {
System.out.println("开始线程阻塞");
LockSupport.park();
System.out.println("结束线程阻塞");
}
}
}CountDownLatch latch = new CountDownLatch(5);
for (int i =0;i<5;i++){
new Thread(new MyTask(latch,i*1000,i)).start();
}
try {
latch.await();
Log.e("WXY--","All the tasks are over.");
} catch (InterruptedException e) {
e.printStackTrace();
}
public class MyTask implements Runnable {
CountDownLatch latch;
int delayTime; // Test
int curThread;
public MyTask(CountDownLatch latch,int delayTime,int curThread) {
this.latch = latch;
this.delayTime = delayTime;
this.curThread = curThread;
}
@Override
public void run() {
try {
Thread.sleep(delayTime);
Log.e("WXY--","current task = " + curThread);
latch.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}| 欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) | 黑马程序员IT技术论坛 X3.2 |