Creating threads in Java
Two things to do to create threads in java:
(1) Create a task (object)
//Creating a task
public class TaskClass implements Runnable {
public TaskClass() { ... }
//Implement the run method in Runnable
void run() {
//things to do in the task }
}
//Runnable interface
public interface Runnable {
void run();
}
(2) Create a thread and combine the task with the thread (object)
1 way
//Create a task class
public class TaskClass implements Runnable {
public TaskClass(...) { ... }
//Implement the run method in Runnable
void run() {
//things to do in the task
}
}
public class ThreadDemo{
public void someMethod(){
//Create an instance of TaskClass
TaskClass task=new TaskClass(...);
//Create a thread
Thread thread=new Thread(task);
//Start a thread
thread.start();
}
}
2 way
//Custom thread class
public class CustomThread extends Thread {
public CustomThread( ) { ... }
//Override the run method in Runnable
void run() {
//things to do in the task
}
}
public class ThreadDemo{
public void someMethod(){
//Create a thread
CustomThread thread1=new CustomThread( );
//Start a thread
thread1.start();
//Create another thread
CustomThread thread2=new CustomThread( );
//Start a thread
thread2.start();
}
}
main Thread
When a program starts, the main Thread automatically starts
The default name of the Thread: main with priority 5
public static void main(String[] args){
System.out.println("Current thread: " + Thread.currentThread());
Thread.currentThread().setName("MyThread");
System.out.println("After name change: " + Thread.currentThread());
}
Example: create threads
public class ThreadDemo1 {
public static void main(String[] args) {
String hw= “do home work”;
String tv= “watch TV”;
DoSomething doHW= new DoSomething( hw );
DoSomething watchTV = new DoSomething( tv );
}
}
public class DoSomething {
private String doWhat;
public DoSomething(String aThing) {
this.doWhat = aThing;
doIt();
}
public void doIt(){
for (int i=0;i<5;i++)
System.out.println(doWhat+": "+i);
}
}
并没有使用多线程
Create threads (solution 1)
public class ThreadDemo1 {
public static void main(String[] args) {
DoSomething doHW= new DoSomething("do home work");
DoSomething watchTV = new DoSomething(“watch TV");
Thread hwThread= new Thread(doHW);
Thread tvThread = new Thread(watchTV);
hwThread.start();
tvThread.start();
}
}
public class DoSomething implements Runnable {
private String doWhat;
public DoSomething(String aThing) {
this.doWhat = aThing;
} public void run(){
for (int i=0;i<5;i++)
System.out.println(doWhat+": "+i);
}
}
Create threads solution 2
public class ThreadDemo2 extends Thread {
String doThing;
ThreadDemo2(String doWhat){
this.doThing=doWhat;
}
public static void main(String[] args) {
String hw= "do home work";
String tv= "watch TV";
ThreadDemo2 thread1=new ThreadDemo2(hw);
ThreadDemo2 thread2=new ThreadDemo2(tv);
thread1.start();
thread2.start();
}
public void run() {
for(int i=0;i<5;i++)
System.out.println(doThing+": "+i);
}
}
Control a Thread
public static void yield():
Causes the currently executing thread object to temporarily pause
Allow other threads to execute(执行)
aThread.yield();
t1.yield();
t2.sleep(1000);
static void sleep(long millis):
Causes the currently executing thread to sleep (block) for the specified number of milliseconds
If the thread is blocked by sleep or wait, an InterruptedException is thrown
try {
aThread.sleep(1000);
//sleep for 1 second
} catch (InterruptedException ex) {
//do sth…
}
interrupt():
Does not stop a thread Set "interrupted" status to true Why interrupt?
After interrupt is set, we can take actions
isInterrupted():
Tests whether this thread has been interrupted.
The interrupted status of the thread is unaffected by this method.
if(isInterrupted()){
Action
}
interrupted():
Tests whether the current thread has been interrupted.
The interrupted status of the thread is cleared by this method.
Returns: true if the current thread has been interrupted; false otherwise.
public class ThreadDemo2 extends Thread {
String doThing;
ThreadDemo2(String doWhat){
this.doThing=doWhat;
}
public static void main(String[] args) {
String hw= "do home work";
String tv= "watch TV";
ThreadDemo2 thread1=new ThreadDemo2(hw);
ThreadDemo2 thread2=new ThreadDemo2(tv);
thread1.start();
thread2.start();
}
public void run() {
for(int i=0;i<5;i++) {
System.out.println(doThing+": "+i);
this.yield();
}
}
}
public class ThreadDemo2 extends Thread {
String doThing;
ThreadDemo2(String doWhat){
this.doThing=doWhat;
}
public static void main(String[] args) {
String hw= "do home work";
String tv= "watch TV";
ThreadDemo2 thread1=new ThreadDemo2(hw);
ThreadDemo2 thread2=new ThreadDemo2(tv);
thread1.start();
thread2.start();
}
public void run() {
for(int i=0;i<5;i++) {
System.out.println(doThing+": "+i);
try {
this.sleep(10);
} catch (InterruptedException ex) {
System.out.println(“sth wrong”);
}
}
}
}
Synchronization
Two or more threads share the same resource Synchronized method:
To make a method synchronized: add the synchronized keyword to its declaration
When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object
end19