`
samsongbest
  • 浏览: 167806 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Java并发/多线程

 
阅读更多

Java多线程

实现线程的两种方法:

a. 继承Thread类,start()启动。

b. 实现Runnable接口,实现run方法。

 

1. 基本线程

package com.sam.thread;

public class SimpleThread extends Thread {
    private int countDown = 5;
    private static int threadCount = 0;

    public SimpleThread() {
        super(" " + ++threadCount); // store the thread name
        start();
    }

    public String toString() {
        return "#" + getName() + ": " + countDown;
    }

    public void run() {
        while (true) {
            System.out.println(this);
            if (--countDown == 0)
                return;
        }
    }

    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            new SimpleThread();
        }
    }
}

package com.sam.thread;

public class SimpleThread extends Thread {
	private int countDown = 5;
	private static int threadCount = 0;

	public SimpleThread() {
		super(" " + ++threadCount); // store the thread name
		start();
	}

	public String toString() {
		return "#" + getName() + ": " + countDown;
	}

	public void run() {
		while (true) {
			System.out.println(this);
			if (--countDown == 0)
				return;
		}
	}

	public static void main(String[] args) {
		for (int i = 0; i < 5; i++) {
			new SimpleThread();
		}
	}
}

结果:

# 1: 5
# 1: 4
# 1: 3
# 1: 2
# 1: 1
# 3: 5
# 3: 4
# 3: 3
# 3: 2
# 3: 1
# 2: 5
# 5: 5
# 5: 4
# 5: 3
# 5: 2
# 5: 1
# 2: 4
# 2: 3
# 2: 2
# 2: 1
# 4: 5
# 4: 4
# 4: 3
# 4: 2
# 4: 1
 

 

 

2.yield(),让步,让其它线程使用CPU,可以让结果更均衡。

package com.sam.thread;

public class YieldThread extends Thread {
	private int countDown = 5;
	private static int threadCount = 0;

	public YieldThread() {
		super(" " + ++threadCount); // store the thread name
		start();
	}

	public String toString() {
		return "#" + getName() + ": " + countDown;
	}

	public void run() {
		while (true) {
			System.out.println(this);
			if (--countDown == 0)
				return;
			yield();
		}
	}

	public static void main(String[] args) {
		for (int i = 0; i < 5; i++) {
			new YieldThread();
		}
	}
}

 结果:

# 1: 5
# 2: 5
# 3: 5
# 1: 4
# 2: 4
# 5: 5
# 3: 4
# 1: 3
# 5: 4
# 3: 3
# 1: 2
# 5: 3
# 3: 2
# 1: 1
# 5: 2
# 4: 5
# 3: 1
# 5: 1
# 2: 3
# 4: 4
# 2: 2
# 2: 1
# 4: 3
# 4: 2
# 4: 1

 

3. sleep, 休眠一段时间再执行

package com.sam.thread;

public class SleepThread extends Thread {
	private int countDown = 5;
	private static int threadCount = 0;

	public SleepThread() {
		super(" " + ++threadCount); // store the thread name
		start();
	}

	public String toString() {
		return "#" + getName() + ": " + countDown;
	}

	public void run() {
		while (true) {
			System.out.println(this);
			if (--countDown == 0)
				return;
			try {
				sleep(100);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) {
		for (int i = 0; i < 5; i++) {
			new SleepThread();
		}
	}
}

 结果:

# 1: 5
# 3: 5
# 2: 5
# 5: 5
# 4: 5
# 1: 4
# 2: 4
# 4: 4
# 3: 4
# 5: 4
# 1: 3
# 2: 3
# 3: 3
# 4: 3
# 5: 3
# 2: 2
# 4: 2
# 3: 2
# 1: 2
# 5: 2
# 1: 1
# 2: 1
# 4: 1
# 3: 1
# 5: 1

 

4. 优先级 setPriority();

package com.sam.thread;

public class PriorityThread extends Thread {
	private int countDown = 5;
	private static int threadCount = 0;

	public PriorityThread(int priority) {
		super(" " + ++threadCount); // store the thread name
		setPriority(priority);
		start();
	}

	public String toString() {
		return "#" + getName() + ": " + countDown;
	}

	public void run() {
		while (true) {
			System.out.println(this);
			if (--countDown == 0)
				return;			
		}
	}

	public static void main(String[] args) {
		new PriorityThread(Thread.MAX_PRIORITY);
		for (int i = 0; i < 5; i++) {
			new PriorityThread(Thread.MIN_PRIORITY);
		}
	}
}

 结果:优先级高的先运行

# 1: 5
# 1: 4
# 1: 3
# 1: 2
# 1: 1
# 3: 5
# 3: 4
# 3: 3
# 3: 2
# 3: 1
# 5: 5
# 5: 4
# 5: 3
# 5: 2
# 5: 1
# 2: 5
# 2: 4
# 2: 3
# 2: 2
# 2: 1
# 4: 5
# 4: 4
# 4: 3
# 6: 5
# 6: 4
# 6: 3
# 6: 2
# 6: 1
# 4: 2
# 4: 1

 

5. 后台线程(daemon)

当所有非后台线程结束,线程终止。如:某个时刻线程都sleep了,程序终止。

package com.sam.thread;

public class DaemonThread extends Thread {
	private int countDown = 5;
	private static int threadCount = 0;

	public DaemonThread() {
		super(" " + ++threadCount); // store the thread name
		setDaemon(true);
		start();
	}

	public String toString() {
		return "#" + getName() + ": " + countDown;
	}

	public void run() {
		while (true) {
			System.out.println(this);
			if (--countDown == 0)
				return;
			try {
				sleep(100);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}

	public static void main(String[] args) {
		for (int i = 0; i < 5; i++) {
			new DaemonThread();
		}
	}
}

 结果:

# 1: 5
# 3: 5
# 5: 5
# 4: 5
# 2: 5

 

6. join()和interrupt()

package com.sam.thread;

class A extends Thread {
	public A() {
		start();
	}
	public void run() {
		try {
			System.out.println("A started.");
			sleep(1000);
		} catch (InterruptedException e) {
			System.out.println("Sleep interrupted");
		}
	}
}

public class JoinThread extends Thread {
	A a;
	public JoinThread(A a) {
		this.a = a;
		start();
	}
	public void run() {
	
		try {
			a.join();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("JoinThread started.");
	}
	public static void main(String[] args) {
		A a = new A();
		JoinThread jt = new JoinThread(a);
		a.interrupt();
	}
}

 结果:

A started.
Sleep interrupted
JoinThread started.

 

7. Runnable接口

package com.sam.thread;

public class RunnableThread implements Runnable {

	private int countDown = 5;

	public String toString() {
		return "#" + Thread.currentThread().getName() + ": " + countDown;
	}

	@Override
	public void run() {
		while (true) {
			System.out.println(this);
			if (--countDown == 0)
				return;
		}
	}

	public static void main(String[] args) {
		for (int i = 1; i <= 5; i++) {
			new Thread(new RunnableThread(), "" + i).start();
		}
	}
}

runnable接口本身不带线程的特性,要运行,还是要建立一个单独的Thread对象。

 

8. 不正确地访问资源

package com.sam.thread;

public class AlwaysEven {
	int i;

	void next() {
		i++;
		i++;
	}

	int get() {
		return i;
	}

	public static void main(String[] args) {
		final AlwaysEven ae = new AlwaysEven();
		new Thread() {
			public void run() {
				while (true) {
					int j = ae.get();
					if (j % 2 != 0) {
						System.out.println(j);
						System.exit(0);
					}
				}
			}
		}.start();
		while (true) {
			ae.next();
		}
	}
}

 结果:

1501

 

9. 解决共享资源竞争

在每个访问共享资源的方法上都要加上synchronized,否则不加的方法会忽视该锁。

package com.sam.thread;

public class AlwaysEven {
	int i;

	synchronized void next() {
		i++;
		i++;
	}

	synchronized int get() {
		return i;
	}

	public static void main(String[] args) {
		final AlwaysEven ae = new AlwaysEven();
		new Thread() {
			public void run() {
				while (true) {
					int j = ae.get();
					if (j % 2 != 0) {
						System.out.println(j);
						System.exit(0);
					}
				}
			}
		}.start();
		while (true) {
			ae.next();
		}
	}
}

 

10. volatile

禁止编译器进行优化,线程不能保留该对象的私有拷贝,影响效率。

 

11. 临界区

防止多个线程访问方法中的部分代码。

synchronized(syncObject) {
    // This code can only be access
    // by one thread at a time
}

 

12. 线程的状态

新建(new)

就绪(Runnable)

死亡(Dead)

阻塞(Blocked)

 

13. notify()

唤醒wait()中的线程。

 

zz

分享到:
评论

相关推荐

    java 多线程并发实例

    在Java编程中,多线程并发是提升程序执行效率、充分利用多核处理器资源的重要手段。本文将基于"java 多线程并发实例"这个主题,深入探讨Java中的多线程并发概念及其应用。 首先,我们要了解Java中的线程。线程是...

    Java 模拟线程并发

    最后,Java并发库还包含了很多其他有用的工具,如Semaphore(信号量)用于控制同时访问特定资源的线程数量,CyclicBarrier(循环屏障)和CountDownLatch(计数器门锁)用于多线程间的协作,以及Lock接口及其实现如...

    Java 高并发多线程编程系列案例代码

    Java 高并发多线程编程系列案例代码 & 教程 & 面试题集锦! !! 包括但不限于线程安全性, atomic包下相关类、CAS原理、Unsafe类、synchronized关键字等的使用及注意事项,

    Java_多线程与并发编程总结.doc

    Java多线程与并发编程是Java开发中至关重要的一部分,它涉及到如何高效地利用CPU资源,以实现程序的并行执行。在操作系统层面,多任务和多进程是通过分配不同的内存空间来实现的,而线程则共享同一进程的内存,这...

    java多线程并发

    java多线程并发的在新窗口

    JAVA多线程并发编程

    Java并发编程是Java开发中的重要领域,特别是在高并发、高性能的应用场景中不可或缺。并发编程能够有效地利用多核处理器资源,提高程序的运行效率,优化系统性能。以下将详细阐述Java并发编程的一些关键知识点。 ...

    java多线程与高并发视频

    java多线程与高并发java多线程与高并发java多线程与高并发

    java多线程查询数据库

    本文将详细探讨如何利用Java的多线程技术和线程池来实现并发查询数据库,以及相关的文件`BatchDataUtil.java`和`BatchDataRunnable.java`可能涉及的关键知识点。 ### 1. 多线程并发查询 多线程并发查询允许我们将一...

    超实用的Java并发多线程教程

    Java并发多线程是Java编程中的重要组成部分,它允许程序同时执行多个任务,极大地提高了程序的效率和响应性。在Java中,多线程主要通过`Thread`类、`Runnable`接口以及`ExecutorService`来实现。下面我们将深入探讨...

    Java多线程与并发库高级应用

    并发库高级应用\多线程\Java

    多线程,高并发.zip

    另外,Java并发API(java.util.concurrent包)提供了一系列高级并发工具,如`ConcurrentHashMap`(线程安全的哈希映射)、`BlockingQueue`(阻塞队列)和`Future`(异步计算结果)。这些工具可以帮助开发者更好地...

    Java多线程并发实战

    ### Java多线程并发实战知识点解析 #### 一、引言 在计算机科学领域,**多线程**和**并发**技术是现代软件开发中不可或缺的一部分。随着处理器核心数量的增加,利用多线程和并发可以显著提高应用程序的性能和响应...

    java多线程分页查询

    多线程是指在一个程序中包含多个可以并发执行的线程,这些线程共享相同的内存空间。通过合理利用多线程技术,可以显著提升程序的运行效率和响应速度。在Java中,可以通过继承`Thread`类或者实现`Runnable`接口来创建...

    java多线程和并发.pdf

    在Java并发编程中,还涉及到多种并发工具类,例如同步容器类和并发容器类。同步容器类使用同步锁来保证线程安全,但可能会影响性能。并发容器类ConcurrentHashMap和CopyOnWriteArrayList等,采用细粒度的锁和弱一致...

    Java Socket/ServerSocket 多线程下聊天室系统

    Java Socket和ServerSocket是Java网络编程中的...总的来说,这个基于Java Socket/ServerSocket的多线程聊天室系统充分展示了Java网络编程的核心技术和设计原则,是学习和实践网络通信、并发处理和对象传输的优秀案例。

    java多线程并发演示

    实现多线程的并发执行,能演示操作系统的时间转轮调度算法对多线程程序执行的影响效果,能控制一个或多个线程的执行情况。

Global site tag (gtag.js) - Google Analytics