侧边栏壁纸
  • 累计撰写 781 篇文章
  • 累计创建 1 个标签
  • 累计收到 1 条评论
标签搜索

创建线程

Dettan
2021-04-10 / 0 评论 / 0 点赞 / 97 阅读 / 1,979 字
温馨提示:
本文最后更新于 2022-04-30,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。
线程start()后可能不会立刻开始执行,只是设置为runable状态,具体取决于cpu的调度。
简写
new Thread(new Runnable() {
	@Override
	public void run() {
		while(true)
			System.out.println("running");
		}
}).start();
有三种方式:
1. 创建一个Thread的子类。
public class MyThread extends Thread {
private static int a = 0;
@Override
public void run() {
	for(;;){
		if(a >= 100){
			return;
		}
		//Thread.yield();
		System.out.println(Thread.currentThread().getName()+ "   "+a);
		a++;
	}
}

}

public static void main(String[] args) {
MyThread myThread = new MyThread();

	MyThread myThread1 = new MyThread();
	MyThread myThread2 = new MyThread();
	
	myThread.start();
	myThread1.start();
	myThread2.start();

}



2. 创建一个实现Runnable接口的子类。
public class MyRunnable implements Runnable {
    private int a = 0;
@Override
public void run() {
    for (int i = 0; i <= 100; i++) {

// try {
// Thread.sleep(3000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
System.out.println(Thread.currentThread().getName() + " " + i);
}
}
}

public static void main(String[] args) {
	// TODO Auto-generated method stub
	//创建线程执行目标类对象
	MyRunnable myRunnable = new MyRunnable();
	
	//创建线程对象,传入线程执行目标类对象
	Thread t1 = new Thread(myRunnable,"花花");
	Thread t2 = new Thread(myRunnable,"红红");
	Thread t3 = new Thread(myRunnable,"兰兰");
	
	//启动线程
	t1.start();
	t2.start();
	t3.start();
}</code></pre></div>            <div style="width: 100%; max-width: 996px; margin-top: 2px;">
            <div style="color: inherit; fill: inherit;">
                <div style="display: flex;">
3. 创建一个实现Callable接口的子类。
FutureTask futureTask=new FutureTask(new Callable() {
    @Override
    public String call() throws Exception {
        Thread.sleep(3000);
        System.out.println("calld方法执行了");
        return "call方法返回值";
    }
});
futureTask.run();
System.out.println("获取返回值: " + futureTask.get());

FutureTask futureTask1=new FutureTask(new Callable() {
@Override
public String call() throws Exception {
Thread.sleep(3000);
System.out.println("calld方法执行了1");
return "call方法返回值1";
}
});
futureTask1.run();
System.out.println("获取返回值1: " + futureTask1.get());



第二种较为常用。
0

评论区