public class Demo_Thread {
public static void main(String[] args) {
ThreadDemo thread1 = new ThreadDemo();
thread1.setName("线程1");
thread1.start();
ThreadDemo thread2 = new ThreadDemo();
thread2.setName("线程2");
thread2.start();
}
}
class ThreadDemo extends Thread{
@Override
public void run(){
for (int i = 1;i<=10;i++){
System.out.println(Thread.currentThread().getName() + ";" + i);
}
}
}
public class Demo_Thread2 {
public static void main(String[] args) {
MyThread thread = new MyThread();
Thread thread1 = new Thread(thread,"线程1");
thread1.start();
Thread thread2 = new Thread(thread,"线程2");
thread2.start();
}
}
class MyThread implements Runnable{
@Override
public void run() {
for (int i = 1;i<=10;i++){
System.out.println(Thread.currentThread().getName() + ";" + i);
}
}
}
public class Demo_Thread3 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
Callable<Object> oneCallable = new Tickets<Object>();
//a.使用FutureTask类包装Callable对象,该FutureTask对象封装了Callable对象的Call方法的返回值
FutureTask<Object> oneTask = new FutureTask<Object>(oneCallable);
//b.创建Thread对象,参数为FutureTask对象
Thread t = new Thread(oneTask,"线程1");
//c.使用FutureTask对象作为Thread对象的target创建并启动线程
t.start();
//d.调用FutureTask对象的get()方法获取子线程执行完毕后的结果
System.out.println(oneTask.get());
}
}
class Tickets<String> implements Callable<Object> {
@Override
public Object call() throws Exception {
for (int i=1;i<=10;i++){
System.out.println(i);
}
return Thread.currentThread().getName()+"线程执行完毕!";
}
}
public class Demo_Thread4 {
public static void main(String[] args){
//创建一个指定数目线程的线程池
ExecutorService pool = Executors.newFixedThreadPool(2);
//将线程放到池子里,并执行
Future<?> submit = pool.submit(new RunnableThread());//有返回值的
pool.submit(new RunnableThread());
//关闭线程池
pool.shutdown();
}
}
class RunnableThread implements Runnable{
@Override
public void run(){
for (int i = 1; i <= 10; i++) {
System.out.println(Thread.currentThread().getName()+":"+ i);
}
}
}
公平锁:表示线程获取锁的顺序是按照线程加锁的顺序来的进行分配的,即先来先得 先进先出顺序。
非公平锁:一种获取锁的抢占机制 是随机拿到锁的,和公平锁不一样的是先来的不 一定先拿到锁,这个方式可能造成某些线程- 直拿不到锁,结果就是不公平的。
例:
本文由 Alicyu 创作,如果您觉得本文不错,请随意赞赏
采用 知识共享署名4.0 国际许可协议进行许可
本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名
原文链接:https://www.alicyu.com/archives/thread
最后更新:2019-10-18 14:41:49
Update your browser to view this website correctly. Update my browser now